【问题标题】:How should I get the length of an IEnumerable? [duplicate]我应该如何获得 IEnumerable 的长度? [复制]
【发布时间】:2018-05-21 11:52:43
【问题描述】:

我正在编写一些代码,并去获取 IEnumerable 的长度。当我写myEnumerable.Count() 时,令我惊讶的是,它没有编译。看完Difference between IEnumerable Count() and Length后,我意识到实际上是Linq给了我扩展方法。

使用 .Length 也不适合我。我使用的是旧版本的 C#,所以也许这就是原因。

获取 IEnumerable 长度的最佳做法是什么?我应该使用 Linq 的 Count() 方法吗?或者有没有更好的方法。 .Length 在更高版本的 C# 中可用吗?

或者如果我需要计数,IEnumerable 是不是该工作的错误工具?我应该改用 ICollection 吗? Count the items from a IEnumerable<T> without iterating? 说 ICollection 是一个解决方案,但是如果您想要一个带有计数的 IEnumerable,它是正确的解决方案吗?

必填代码sn-p:

var myEnumerable = IEnumerable<Foo>();

int count1 = myEnumerable.Length; //Does not compile

int count2 = myEnumerable.Count(); //Requires Linq namespace

int count3 = 0; //I hope not
for(var enumeration in myEnumerable)
{
    count3++;
}

【问题讨论】:

  • 看起来您可能希望使用IReadOnlyCollection&lt;T&gt;,它为您提供IEnumerable&lt;T&gt;.Count 属性的组合。
  • IEnumerable 定义了可用于迭代集合的迭代器。它不知道收藏有多大。如果您需要知道集合的大小,那么IEnumerable 是不够的,您需要找到其他具有跟踪元素数量功能的结构,例如IList
  • 如果您拥有为您提供 IEnumerable 的代码(假设这是您自己方法的返回类型) - 您应该考虑将其更改为返回更合适的类型。

标签: c# performance linq count ienumerable


【解决方案1】:

如果您需要读取 IEnumerable&lt;T&gt; 中的项目数,您必须调用扩展方法 Count通常(查看 Matthew 评论)将在内部迭代元素序列,它将返回序列中的项目数。没有其他更直接的方法了。

如果你知道你的序列是一个数组,你可以转换它并使用Length属性读取它们的项目数。

不,在以后的版本中没有这种方法。

Count方法的实现细节请看here

【讨论】:

  • 请注意,Linq.Count() 足够聪明,可以识别实现 ICollection&lt;T&gt; 的数组和列表,以避免迭代,只需强制转换并返回 Count,即 O(1) 而不是 O(N)手术。 See the source code.
  • @MatthewWatson 感谢您指出这一点。
  • 这一切都很好,但是考虑到possible duplicate 的答案同样涵盖了这些选项和实现细节,这会造成很多混乱。
猜你喜欢
  • 2017-03-31
  • 1970-01-01
  • 1970-01-01
  • 2015-06-08
  • 1970-01-01
  • 2020-12-25
  • 2017-11-22
  • 1970-01-01
相关资源
最近更新 更多