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)
Use the Sum()
method:
int summedCount = Lists.Sum(l => l.Count);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With