Reputation: 3364
I am trying to learn lambda expression from Microsoft website and I am trying to apply it to a scenario I create to get deeper understanding of what the site is trying to demonstrate. I stumble in the aggregate function that associates with linq and lambda. Please advise what is the correct syntax for what I am trying to achieve. Basically, I have a class called item which has 3 properties: category, ID and weight. A category can have multiple IDs associated with it and I am thinking of getting the total weight of a category which is the sum of all individual weight of each IDs that has the category I specified. More specifically, this is the extract of my structure:
class item
{
public int NodeID
{ get; set; }
public int Weight
{ get; set; }
public int Category
{ get; set; }
}
I have the following dictionary:
Dictionary<int,item> _itemsReceivedList=new Dictionary<int,item>();
And this is where I tried to get the total weight of a category c:
_itemsReceivedList.Select(x=>x.Value.Category==c)
.Sum( what should I put here for the predicate? )
I wanted to sum the weight of each item that has category c. Please advise. Thanks!
Upvotes: 1
Views: 1969
Reputation: 24780
Write this
_itemsReceivedList.Where(x=>x.Value.Category==c).Sum(x => x.Weight);
Upvotes: 2
Reputation: 7303
int weight = _itemsReceivedList.Where(x => x.Value.Category == c)
.Select(s => s.Value)
.Sum(item => item.Weight);
I assume that c
is declared somewhere else as an int
Upvotes: 3
Reputation: 116108
var sum = _itemsReceivedList
.Where(x=>x.Value.Category==c)
.Sum(x=>x.Value.Weight);
Upvotes: 3