How to make a SUM of Dictionary Value nested into a list with LINQ?
I have a product object declared as :
Product {
int ProductID;
string ProductName;
int ProductTypeID;
string ProductTypeName;
int UnitsSold
Dictionary <string, int> UnitsSoldByYear;
}
I want to make a sum on UnitsSold and UnitsSoldByYear properties with a Linq query but I didn't k开发者_运维百科now how to make this kind of sum on a dictionary ! Here is my begining linq query code :
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
}
Thank you for your help !
To sum your inner dictionary just do:
DictSum = pt.Select(x => x.UnitsSoldByYear.Values.Sum()).Sum()
or equally:
DictSum = pt.Sum(x => x.UnitsSoldByYear.Values.Sum())
EDIT:
according to the OP comment, this creates a dictionary with the sum by each key:
DictSum = pt.SelectMany(kvp => kvp.UnitsSoldByYear)
.GroupBy(kvp => kvp.Key)
.ToDictionary(grp => grp.Key,grp => grp.Sum(kvp => kvp.Value))
精彩评论