List< List< T>>中元素的数量计数. [英] Count number of element in List<List<T>>

查看:80
本文介绍了List< List< T>>中元素的数量计数.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个List<List<T>>. 如何以最快的方式计算其中的所有元素,就好像它是单个List<T>一样?

I have a List<List<T>>. How can I count all the elements in this as if it was a single List<T> in the fastest way?

到目前为止,我已使用

List<int> result = listOfLists
  .SelectMany(list => list)
  .Distinct()
  .ToList().Count;

但这实际上会创建一个列表,然后对元素进行计数,这不是一个好主意.

but this actually creates a list and then counts the element which is not a very good idea.

推荐答案

如果您需要消除列表之间的重复项,我建议使用HashSet进行简单的嵌套循环.它将SelectMany和Distinct操作组合到集合插入逻辑中,并且由于HashSet具有O(1)查找时间,因此应该更快.内部Distinct()可能实际上使用了类似的东西,但这完全省略了单个列表的构造.

I would recommend a simple, nested loop with a HashSet if you need to eliminate duplicates between lists. It combines the SelectMany and Distinct operations into the set insertion logic and should be faster since the HashSet has O(1) lookup time. Internally Distinct() may actually use something similar, but this omits the construction of the single list entirely.

var set = new HashSet<T>();
foreach (var list in listOfLists)
{
    foreach (var item in list)
    {
        set.Add(item);
    }
}
var result = set.Count;

这篇关于List&lt; List&lt; T&gt;&gt;中元素的数量计数.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆