JMarsch
JMarsch

Reputation: 21751

What's the LINQ'ish way to do this

Say, I have an array of lists, and I want to get a count of all of the items in all of the lists. How would I calculate the count with LINQ? (just general curiosity here)

Here's the old way to do it:


List<item>[] Lists = // (init the array of lists)
int count = 0;
foreach(List<item> list in Lists)
  count+= list.Count;
return count;

How would you LINQify that? (c# syntax, please)

Upvotes: 10

Views: 533

Answers (3)

jrista
jrista

Reputation: 32990

Use the Sum() method:

int summedCount = Lists.Sum(l => l.Count);

Upvotes: 27

Cheick
Cheick

Reputation: 2204

And if you want to be fancy

 int summedCount = Lists.Aggregate(0, (acc,list) => acc + list.Count);

But the first answer is definitely the best.

Upvotes: 4

Mike Two
Mike Two

Reputation: 46183

I like @jrista's answer better than this but you could do

int summedCount = Lists.SelectMany( x => x ).Count();

Just wanted to show the SelectMany usage in case you want to do other things with a collection of collections.

Upvotes: 12

Related Questions