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开发者_如何学Go 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
精彩评论