IEnumerable的计数()和长度的区别长度、区别、IEnumerable

2023-09-02 01:55:25 作者:血溢满衣袖。

什么是的IEnumerable 计数()之间的主要区别长度

What are the key differences between IEnumerable Count() and Length?

推荐答案

通过调用指望的IEnumerable< T> 我假设你指的是扩展方法计数 System.Linq.Enumerable 长度不在的IEnumerable℃的方法; T> 而是在净数组类型的属性,如 INT []

By calling Count on IEnumerable<T> I'm assuming you're referring to the extension method Count on System.Linq.Enumerable. Length is not a method on IEnumerable<T> but rather a property on array types in .Net such as int[].

不同的是性能。该长度属性被保证是一个O(1)操作。的的复杂计数扩展方法有所不同基于对象的运行时类型。它会尝试转换为多种类型的支持O(1)长度查询像的ICollection&LT; T&GT; 通过计数属性。如果没有可用的,然后它会枚举所有项目,并计算它们具有的O(N)的复杂性。

The difference is performance. TheLength property is guaranteed to be a O(1) operation. The complexity of the Count extension method differs based on runtime type of the object. It will attempt to cast to several types which support O(1) length lookup like ICollection<T> via a Count property. If none are available then it will enumerate all items and count them which has a complexity of O(N).

例如

int[] list = CreateSomeList();
Console.WriteLine(list.Length);  // O(1)
IEnumerable<int> e1 = list;
Console.WriteLine(e1.Count()); // O(1) 
IEnumerable<int> e2 = list.Where(x => x <> 42);
Console.WriteLine(e2.Count()); // O(N)

E2 被实现为一个C#迭代器不支持O(1)计算,因此该方法计数必须枚举整个集合来确定它有多长。

The value e2 is implemented as a C# iterator which does not support O(1) counting and hence the method Count must enumerate the entire collection to determine how long it is.

 
精彩推荐
图片推荐