Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the LINQ'ish way to do this

Tags:

c#

linq

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)

like image 685
JMarsch Avatar asked Sep 24 '09 23:09

JMarsch


3 Answers

Use the Sum() method:

int summedCount = Lists.Sum(l => l.Count);
like image 165
jrista Avatar answered Nov 20 '22 03:11

jrista


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.

like image 12
Mike Two Avatar answered Nov 20 '22 03:11

Mike Two


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.

like image 4
Cheick Avatar answered Nov 20 '22 04:11

Cheick