【问题标题】:Is it possible to use Linq to get a total count of items in a list of lists?是否可以使用 Linq 获取列表列表中的项目总数?
【发布时间】: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();

【问题讨论】:

    标签: c# linq aggregate


    【解决方案1】:

    一个简单的Enumerable.Sum 就足够了。

    var totalFoos = fooInfo.Sum(childList => childList.Count); 
    

    它计算通过对输入序列的每个元素调用变换函数获得的 Int32 值序列的总和。

    您可以使用SelectMany,但这样的性能会更好。

    【讨论】:

    • 我几乎感到尴尬,它是如此简单,我没有想到它! (是的,我意识到在我提出并接受该评论近七年后我才添加此评论。有人投票支持并让我回来。哈哈)
    【解决方案2】:

    使用SelectMany 和Count:

    var nbOfItems = source.SelectMany(x => x).Count();
    

    或Select、Count和Sum:

    var nbOfItems = source.Select(x => x.Count()).Sum();
    

    后者会表现得更好,因为它不会像SelectMany那样枚举所有项目。

    【讨论】:

    • @NikhilAgrawal Enumerable&lt;T&gt;.Count() 检查目标是否实现了ICollection&lt;T&gt;(因此具有Count 属性),如果实现则使用它。
    • 是的。有效点。我担心的是使用List.Count 而不是IEnumerable.Count。这将使您的查询更轻松。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    • 2010-09-19
    • 1970-01-01
    相关资源
    最近更新 更多