Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between IEnumerable Count() and Length

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

like image 480
balalakshmi Avatar asked Mar 26 '10 07:03

balalakshmi


People also ask

What is the difference between length and count?

Length is a property returning the number of elements in an Array . Count() is a LINQ extension that does the same on an IEnumerable . Optionally, it can take a predicate as parameter, and will return the number of elements that satisfy it.

How is IEnumerable count calculated?

IEnumerable has not Count function or property. To get this, you can store count variable (with foreach, for example) or solve using Linq to get count.

Does IEnumerable have count?

IEnumerable doesn't have a Count method.

What is the difference between count and count () in C#?

Count() is there as an extension method from LINQ - Count is a property on List s, actual . NET collection objects. As such, Count() will almost always be slower, since it will enumerate the collection / queryable object. On a list, queue, stack etc, use Count .


1 Answers

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[].

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).

For example

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) 

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.

like image 190
JaredPar Avatar answered Sep 28 '22 00:09

JaredPar