Sum amount using Linq in <List<Dictionary<string, int>> – Education Career Blog

I have a generic list declared as so:

List<Dictionary<string, int>> sales;

The string will be a product name and the int the number of units sold. I want to group by productname and sum the total sales. So i can see the number of units sold for each product.

How would i do this using linq?

Thanks!

,

This will give you the result as a dictionary where the key is the product name and the value is the total number of units sold.

var result =
    sales.SelectMany(d => d)                        // Flatten the list of dictionaries
         .GroupBy(kvp => kvp.Key, kvp => kvp.Value) // Group the products
         .ToDictionary(g => g.Key, g => g.Sum());   // Sum each group

Leave a Comment