tags:

views:

184

answers:

3

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)

+27  A: 

Use the Sum() method:

int summedCount = Lists.Sum(l => l.Count);
jrista
true LINQ would use: var summedCount = ...
Travis Heseman
@Travis: not at all. Var is not a requirement in any situation except in the use of anonymous types. In all other cases, it is 'true' linq to use var or a strong type as the developer pleases, there is no practical difference for all intents and purposes.
jrista
+12  A: 

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.

Mike Two
Nice way to describe SelectMany. +1
jrista
+4  A: 

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.

Johnny Blaze