Reputation: 6021
I need to Sum values in a column of a list of objects joined to the list I have. For example, I have classes A and B, and B has a value I want to Sum:
class A
{
//props
}
class B
{
//props
decimal ValToSum { get; set; }
}
A has a relation with B so that each A can have many Bs joined.
And I have a list of As from my data context:
IEnumerable<A> myList;
// obtain myList from DataContext
Now I want to sum ValToSum properties of every B resulting from the join with A.
Something like:
myList.Bs.Sum(x => x.ValToSum);
How can I access the list of all Bs related to As in myList?
Upvotes: 0
Views: 82
Reputation: 46909
Use SelectMany
to flatten the sequances into one and than use Sum
myList.SelectMany(x => x.Bs).Sum(x => x.ValToSum);
Upvotes: 2