How to count the elements of a list in a list in a list using LINQ?
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)));
精彩评论