我们有一个简单的结构,它只是一个列表的列表,就像这样......
var fooInfo = new List<List<Foo>>();
我想知道是否有一种简单的方法可以使用 linq 返回内部列表中所有项目的总数。例如,如果我们有这个...
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());
...我们将有三个列表,分别包含两项、一项和四项,这意味着“Foo”对象总数为七个。这是我希望通过 linq 检索的数字,而不必编写我们自己的循环代码并手动计算它们。
例如
var totalFoos = fooInfo.LINQToGetTotalFoos();
而不是......
int totalFoos = 0;
foreach(var childList in fooInfo)
totalFoos += childList.Count();
最佳答案
一个简单的Enumerable.Sum就足够了。
var totalFoos = fooInfo.Sum(childList => childList.Count);
它计算通过对输入序列的每个元素调用转换函数获得的 Int32 值序列的总和。
您可以使用 SelectMany
但这样的性能会更好。
关于c# - 是否可以使用 Linq 获取列表列表中的项目总数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24729744/