c# - 是否可以使用 Linq 获取列表列表中的项目总数?

标签 c# linq aggregate

我们有一个简单的结构,它只是一个列表的列表,就像这样......

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/

相关文章:

来自 C DLL 回调的 C# 跨线程 UI 操作

c# - 如何制作精简的 PropertyGrid

c# - 嵌套 Linq 分组依据

node.js - 尝试使用聚合将集合复制到另一个集合时出错。

R:如何根据列表中的列条件汇总(聚合)dfs 的值?

c# - 如何将 Gridview 的选定行值插入 .net 中的数据库

c# - 如何编写一个长时间运行的事件来调用 WF 4.0 中的 Web 服务

c# - DISTINCT() 和 ORDERBY 问题

c# - linq中的动态排序

python - Pandas:计算列中的一些值