我有一个产品对象声明为:
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
}
感谢您的帮助!
答案 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))