开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜