如何使用LINQ将字典值的SUM嵌套到列表中?

时间:2010-12-22 11:44:26

标签: c# linq

我有一个产品对象声明为:

Product {
   int ProductID;
   string ProductName;
   int ProductTypeID;
   string ProductTypeName;
   int UnitsSold
   Dictionary <string, int> UnitsSoldByYear;
}

我想用Linq查询对UnitsSold和UnitsSoldByYear属性进行总结,但我不知道如何在字典上进行这种求和! 这是我开始的linq查询代码:

var ProductTypeSum = from i in ProductsList
                     group i by new { i.ProductTypeID, i.ProductTypeName} into pt
                     select new
                         {
                             ProductTypeID= pt.Key.ProductTypeID,
                             ProductTypeName= pt.Key.ProductTypeName,
                             UnitsSoldSum= pt.Sum(i => i.UnitsSold),
                             // How to make a Dictionary sum here
                            }

感谢您的帮助!

1 个答案:

答案 0 :(得分:13)

总结你的内心词典:

DictSum = pt.Select(x => x.UnitsSoldByYear.Values.Sum()).Sum()

或同等地:

DictSum = pt.Sum(x => x.UnitsSoldByYear.Values.Sum())

修改

根据OP评论,这会创建一个字典,其中包含每个键的总和:

DictSum = pt.SelectMany(kvp => kvp.UnitsSoldByYear)
            .GroupBy(kvp => kvp.Key)
            .ToDictionary(grp => grp.Key,grp => grp.Sum(kvp => kvp.Value))