想象一下以下列表:
List<List<List<String>>> listRoot = new List<List<List<String>>>();
我想计算第一个和第二个列表的元素并返回累计值:
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;
我只是想知道是否可以使用LINQ做到这一点?
答案 0 :(得分:4)
listRoot.SelectMany(l => l.SelectMany(li => li)).Count()
答案 1 :(得分:4)
int totalCount = listRoot.Sum(x => x.Count + x.Sum(y => y.Count));
答案 2 :(得分:4)
这应该这样做:
int firstListCounter = listRoot.Sum(f => f.Count);
int secondListCount = listRoot.Sum(f => f.Sum(s => s.Count));
答案 3 :(得分:3)
int iTotalListCounter = listRoot.Sum(x => (x.Count + x.Sum(y => y.Count)));