【发布时间】:2014-09-03 23:15:02
【问题描述】:
我们有一个简单的结构,它只是一个列表的列表,就像这样......
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();
【问题讨论】: