使用< List< Dictionary< string,int> [英] Sum amount using Linq in <List<Dictionary<string, int>>

查看:61
本文介绍了使用< List< Dictionary< string,int>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个声明为这样的通用列表:

I have a generic list declared as so:

List<Dictionary<string, int>> sales;

该字符串将是产品名称,而int是销售的单位数.我想按产品名称分组并汇总总销售额.这样我就可以看到每种产品的销售数量.

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.

我将如何使用linq做到这一点?

How would i do this using linq?

谢谢!

推荐答案

这将为您提供作为字典的结果,其中的键是产品名称,值是售出的总数量.

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

这篇关于使用&lt; List&lt; Dictionary&lt; string,int&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆