开发者

Sum amount using Linq in <List<Dictionary<string, int>>

开发者 https://www.devze.com 2023-01-20 14:34 出处:网络
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

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
0

精彩评论

暂无评论...
验证码 换一张
取 消