Problem overview
Three arrays line up by position: items holds the names, prices holds each price and categories holds the category of each item. Position 0 is the apple, a food costing 2; position 2 is the shirt, clothes costing 25.
The program adds up the prices for each category and prints one line per category, in the format Category: $total, sorted alphabetically by category name. For the starting data the output is:
Clothes: $65
Food: $6
Clothes are the shirt (25) and the pants (40), which make 65. Food is the apple (2), the bread (3) and the banana (1), which make 6.
Approach: accumulate in a dictionary, then sort the keys
The problem has two parts. First, totals must be accumulated per category. A Dictionary<string, int> fits: the key is the category and the value is the running total. Each item adds its price to its category's entry.
Second, the output must be in alphabetical order. A dictionary gives no order you can rely on. Printing it as is could list Food before Clothes. So the program copies the keys into a list, sorts the list, and builds the lines by looking each key up in the dictionary.
Following the loop one item at a time, the total of the item's category changes like this:
0 Apple Food -> 2
1 Bread Food -> 5
2 Shirt Clothes -> 25
3 Banana Food -> 6
4 Pants Clothes -> 65
The first item of each category starts from 0, because the category has no entry yet. After the loop, the dictionary holds Food with 6 and Clothes with 65.
Step by step
- Create the dictionary.
totalsis an emptyDictionary<string, int>. - Loop by position. A
forloop withifrom 0 whilei < items.Lengthvisits the same position in all three arrays. - Read the category. Inside the loop,
catiscategories[i]. - Add the price. Set
totals[cat]to its current value plusprices[i]. When the category isn't a key yet, there is no value to read, so a ternary ontotals.ContainsKey(cat)supplies 0 instead. - Prepare the rows. After the loop, create an empty
List<string>namedlines. A list grows as rows are added. - Copy the keys.
keysis anew List<string>(totals.Keys). Only a list can be sorted. - Sort them.
keys.Sort()rearranges the list in place. - Visit each category in order. A
foreachloop takes each value ofkeysascat. - Add one row.
lines.Add(cat + ": $" + totals[cat]). The+turns theintinto text when it joins it to a string. - Join the rows.
string.Join("\n", lines)puts a newline between each two rows, so there is none after the last one. - Print
resultwithConsole.WriteLine.
The solution in C#
string[] items = {"Apple", "Bread", "Shirt", "Banana", "Pants"};
int[] prices = {2, 3, 25, 1, 40};
string[] categories = {"Food", "Food", "Clothes", "Food", "Clothes"};
Dictionary<string, int> totals = new Dictionary<string, int>();
for (int i = 0; i < items.Length; i++) {
string cat = categories[i];
totals[cat] = (totals.ContainsKey(cat) ? totals[cat] : 0) + prices[i];
}
List<string> lines = new List<string>();
List<string> keys = new List<string>(totals.Keys);
keys.Sort();
foreach (string cat in keys) {
lines.Add(cat + ": $" + totals[cat]);
}
string result = string.Join("\n", lines);
Console.WriteLine(result);
The C# details worth a closer look:
- Reading a missing key throws. With a key that isn't there,
totals["Toys"]throws aKeyNotFoundExceptionwith the message The given key 'Toys' was not present in the dictionary. That is why the read is guarded byContainsKey. In the ternary,totals[cat]is only evaluated when the condition is true. - Assigning through the indexer.
totals[cat] = ...adds the key if it is new and replaces the value if it exists, so the same line handles the first and the later items of a category. - The same name in two loops.
catis declared inside theforbody and again as theforeachvariable. That is legal because each one lives only inside its own loop. - Sorting the list, not the dictionary.
Sort()is a method ofList<T>, which is why the keys are copied first. It sorts the list in place and returns nothing. - Join takes the list.
string.Join(separator, lines)accepts any collection of strings, including aList<string>.
Edge cases and common mistakes
- Reading before the key exists. Writing
totals[cat] += prices[i]throws theKeyNotFoundExceptionabove for the first item of each category. - Printing the dictionary directly. Looping over
totals.Keyswithout sorting printedFoodfirst andClothessecond for this data, the reverse of the required order. - Letter case when sorting.
Sort()on strings uses the current culture's rules, which putclothesbeforeClothesbeforefoodbeforeFood. WithStringComparer.Ordinal, the list becomesClothes,Food,clothes,food: every uppercase letter before every lowercase one. The categories in this lesson all start with a capital letter, so both orders agree. - A trailing newline. The separator in
string.Joingoes only between rows, soresultdoesn't end with a newline.Console.WriteLineadds the final one when printing. - Mixing up the loops. The first loop runs over positions with
i, because it needs the price and category at the same position. The second runs over the sorted categories, because each row needs the dictionary's total, not an array element.
