【发布时间】: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<T>,它为您提供IEnumerable<T>与.Count属性的组合。 -
IEnumerable定义了可用于迭代集合的迭代器。它不知道收藏有多大。如果您需要知道集合的大小,那么IEnumerable是不够的,您需要找到其他具有跟踪元素数量功能的结构,例如IList -
如果您拥有为您提供
IEnumerable的代码(假设这是您自己方法的返回类型) - 您应该考虑将其更改为返回更合适的类型。
标签: c# performance linq count ienumerable