Start learning free

LESSON 193 OF 289 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V6 in C#: Group by Category with a Dictionary

Practice Read the full explanation

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 Dictionary totals that 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 (so Clothes comes before Food).
  • Join the lines with a newline "\n" into one string result, then print it with Console.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);

STEP 1 OF 11
    Ctrl + Enter to check

    C# · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V6 in C#, explained

    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

    1. Create the dictionary. totals is an empty Dictionary<string, int>.
    2. Loop by position. A for loop with i from 0 while i < items.Length visits the same position in all three arrays.
    3. Read the category. Inside the loop, cat is categories[i].
    4. Add the price. Set totals[cat] to its current value plus prices[i]. When the category isn't a key yet, there is no value to read, so a ternary on totals.ContainsKey(cat) supplies 0 instead.
    5. Prepare the rows. After the loop, create an empty List<string> named lines. A list grows as rows are added.
    6. Copy the keys. keys is a new List<string>(totals.Keys). Only a list can be sorted.
    7. Sort them. keys.Sort() rearranges the list in place.
    8. Visit each category in order. A foreach loop takes each value of keys as cat.
    9. Add one row. lines.Add(cat + ": $" + totals[cat]). The + turns the int into text when it joins it to a string.
    10. Join the rows. string.Join("\n", lines) puts a newline between each two rows, so there is none after the last one.
    11. Print result with Console.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 a KeyNotFoundException with the message The given key 'Toys' was not present in the dictionary. That is why the read is guarded by ContainsKey. 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. cat is declared inside the for body and again as the foreach variable. That is legal because each one lives only inside its own loop.
    • Sorting the list, not the dictionary. Sort() is a method of List<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 a List<string>.

    Edge cases and common mistakes

    • Reading before the key exists. Writing totals[cat] += prices[i] throws the KeyNotFoundException above for the first item of each category.
    • Printing the dictionary directly. Looping over totals.Keys without sorting printed Food first and Clothes second for this data, the reverse of the required order.
    • Letter case when sorting. Sort() on strings uses the current culture's rules, which put clothes before Clothes before food before Food. With StringComparer.Ordinal, the list becomes Clothes, 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.Join goes only between rows, so result doesn't end with a newline. Console.WriteLine adds 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.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free