<分区>
我正在编写一些代码,然后去获取 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,它是正确的解决方案吗?
强制性代码片段:
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++;
}