Difference between IEnumerable Count() and Length

后端 未结 3 1598
感动是毒
感动是毒 2020-11-30 01:21

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

3条回答
  •  情深已故
    2020-11-30 02:25

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

    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 via a Count property. If none are available then it will enumerate all items and count them which has a complexity of O(N).

    For example

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

    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.

提交回复
热议问题