We have a simple structure which is just a list of lists, like so...
var fooInfo = new List<List<Foo>>();
I'm wondering if there's a simple way we can use linq to return the total of all items from the inner lists. For example, if we had this...
fooInfo.add(new List<Foo>()); // First list within the outer list
fooInfo.add(new List<Foo>()); // Second list within the outer list
fooInfo.add(new List<Foo>()); // Third list within the outer list
// Add two items to the first inner list
fooInfo[0].add(new Foo());
fooInfo[0].add(new Foo());
// Add one item to the second inner list
fooInfo[1].add(new Foo());
// Add four items to the third inner list
fooInfo[2].add(new Foo());
fooInfo[2].add(new Foo());
fooInfo[2].add(new Foo());
fooInfo[2].add(new Foo());
...we would have three lists with two, one and four items respectively, meaning the total 'Foo' objects are seven. That's the number I'm hoping to retrieve via linq rather than having to write our own looping code and manually tally them up.
e.g.
var totalFoos = fooInfo.LINQToGetTotalFoos();
rather than....
int totalFoos = 0;
foreach(var childList in fooInfo)
totalFoos += childList.Count();
In LINQ, you can find the sum of the given numeric elements by using the Sum() method. This method calculates the sum of the numeric value present in the given sequence. It does not support query syntax in C#, but it supports in VB.NET. It is available in both Enumerable and Queryable classes in C#.
LINQ with ArrayListYou don't need to specify array size unlike traditional array and the size grows as you will add more element into it. However, it is slower than Array but it is more useful when you work with collection. Here, in this example, we will learn how to process data in ArrayList using LINQ C#.
Items select new { Sum(p. Total), Sum(p. Done)};
The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.
A simple Enumerable.Sum would suffice.
var totalFoos = fooInfo.Sum(childList => childList.Count);
It computes the sum of the sequence of Int32 values that are obtained by invoking a transform function on each element of the input sequence.
You can use SelectMany
but performance of this would be better.
Use SelectMany
and Count
:
var nbOfItems = source.SelectMany(x => x).Count();
or Select
, Count
and Sum
:
var nbOfItems = source.Select(x => x.Count()).Sum();
The latter will perform better, because it will not enumerate over all the items like SelectMany
will.
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