Andrea Colleoni
Andrea Colleoni

Reputation: 6021

Linq2Sql: Sum of joined column

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

Answers (3)

Magnus
Magnus

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

Peter Porfy
Peter Porfy

Reputation: 9030


var sum = myList.SelectMany(i => i.Bs).Sum(i => i.ValToSum);

Upvotes: 2

lukiffer
lukiffer

Reputation: 11293

var sum = myList.Bs.Select(x => x.ValToSum).Sum();

Upvotes: 0

Related Questions