Mar*_*eIV 12 c# linq aggregate
我们有一个简单的结构,它只是一个列表列表,就像这样......
var fooInfo = new List<List<Foo>>();
Run Code Online (Sandbox Code Playgroud)
我想知道是否有一种简单的方法可以使用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());
Run Code Online (Sandbox Code Playgroud)
...我们将有三个列表分别包含两个,一个和四个项目,这意味着总共'Foo'对象是七个.这是我希望通过linq检索的数字,而不是必须编写我们自己的循环代码并手动计算它们.
例如
var totalFoos = fooInfo.LINQToGetTotalFoos();
Run Code Online (Sandbox Code Playgroud)
而不是....
int totalFoos = 0;
foreach(var childList in fooInfo)
totalFoos += childList.Count();
Run Code Online (Sandbox Code Playgroud)
Nik*_*wal 15
一个简单的Enumerable.Sum就足够了.
var totalFoos = fooInfo.Sum(childList => childList.Count);
Run Code Online (Sandbox Code Playgroud)
它计算通过在输入序列的每个元素上调用转换函数获得的Int32值序列的总和.
你可以使用SelectMany但性能会更好.
使用SelectMany和Count:
var nbOfItems = source.SelectMany(x => x).Count();
Run Code Online (Sandbox Code Playgroud)
或者Select,Count和Sum:
var nbOfItems = source.Select(x => x.Count()).Sum();
Run Code Online (Sandbox Code Playgroud)
后者会表现得更好,因为它不会像SelectMany遗嘱那样枚举所有项目.