Use a Dictionary to accumulate totals per category while looping over parallel arrays, then list the categories sorted by name.
You start with:
string[] items = {"Apple", "Bread", "Shirt", "Banana", "Pants"};
int[] prices = {2, 3, 25, 1, 40};
string[] categories = {"Food", "Food", "Clothes", "Food", "Clothes"};
Build:
Clothes: $65 Food: $6
Rules:
- Build a
Dictionarytotalsthat maps each category to the sum of the prices of its items. - Loop with an index. For each item, add its price to the total of
categories[i]; a category you have not seen yet counts as 0. - Make one line per category, in the format
"Category: $total", sorted alphabetically by category name (soClothescomes beforeFood). - Join the lines with a newline
"\n"into one stringresult, then print it withConsole.WriteLine(result).
Use
totals.ContainsKey(cat) ? totals[cat] : 0 as the starting value: reading a missing key with [] would throw.
Copy the keys into a
List<string> and call Sort() on it, then loop over the sorted list.
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);
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
