tags:

views:

175

answers:

4

Imagine the following list:

List<List<List<String>>> listRoot = new List<List<List<String>>>();

I want to count the elements of the first and the second list and return the accumulated value:

    int iFirstListCounter = 0;
    int iSecondListCounter = 0;

    foreach (List<List<String>> listFirst in listRoot)
    {

        iFirstListCounter += listFirst.Count;

        foreach (List<String> listSecond in listFirst)
        {

            iSecondListCounter += listSecond.Count;

        }

    }

    return iFirstListCounter + iSecondListCounter;

I just wonder if it's possible to do this using LINQ?

+3  A: 
listRoot.SelectMany(l => l.SelectMany(li => li)).Count()
Yuriy Faktorovich
Definitely better than the accepted answer.
Joel Coehoorn
Joel, since neither this answer nor the accepted answer correctly answer the stated problem, which one is "better" seems academic at best. :)
Eric Lippert
Although about as readable.
Yuriy Faktorovich
Also, this technique is asymptotitally slow as the innermost lists become large. If you're in that scenario then you can take advantage of the fact that a list already knows its count.
Eric Lippert
@Eric Lippert: Technically he didn't mention fastest, but thats true and I agree with Guffas answer then.
Yuriy Faktorovich
This doesn't return the right value. It only counts the elements in the list containing the strings.
timo2oo8
@timo2oo8: Your question was "How to count the elements of a list in a list in a list using LINQ?". I take it what you were really looking for is iFirstListCounter + iSecondListCounter, which was the selected answer.
Yuriy Faktorovich
+4  A: 
int totalCount = listRoot.Sum(x => x.Count + x.Sum(y => y.Count));
Adam Robinson
+4  A: 

This should do it:

int firstListCounter = listRoot.Sum(f => f.Count);
int secondListCount = listRoot.Sum(f => f.Sum(s => s.Count));
Guffa
+3  A: 
int  iTotalListCounter = listRoot.Sum(x => (x.Count + x.Sum(y => y.Count)));
DreamWalker
The original poster requested two values. You're only supplying one of them.
Eric Lippert
@Eric, I think he only requested the total sum, though you're right in that he does have variables for both. The better question is why was this the accepted answer when it's identical to mine? ;)
Adam Robinson
Ah, I see what you mean. This is a confusingly worded question, and it's not clear to me why the sum is even relevant. It seems like an odd thing to sum.
Eric Lippert
@Adam: Because you're not using his weird naming conventions.
Yuriy Faktorovich
@Adam Robinson: It's because you didn't prefix your variable name with `i`. :)
Joshua
iOh iI isee. iWee ishould iof icourse ifollow iany iconvention ithat ithe iOP ihappens ito ifollow... ;)
Guffa