开发者

How to count the elements of a list in a list in a list using LINQ?

开发者 https://www.devze.com 2022-12-08 02:18 出处:网络
Imagine the following list: List<List<List<String>>> listRoot = new List<List<List<String>>>();

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 wond开发者_运维问答er if it's possible to do this using LINQ?


listRoot.SelectMany(l => l.SelectMany(li => li)).Count()


int totalCount = listRoot.Sum(x => x.Count + x.Sum(y => y.Count));


This should do it:

int firstListCounter = listRoot.Sum(f => f.Count);
int secondListCount = listRoot.Sum(f => f.Sum(s => s.Count));


int  iTotalListCounter = listRoot.Sum(x => (x.Count + x.Sum(y => y.Count)));
0

精彩评论

暂无评论...
验证码 换一张
取 消