Differences between Array.Length and Array.Count()

arrays, c#

Solution

`array.Count()` is actually a call to the `Enumerable.Count<T>(IEnumerable<T>)` extension method.

Since this method takes an `IEnumerable<T>` (as opposed to `ICollection<T>`, which has a `Count` property), it needs to loop through the entire sequence to figure out how big it is.

However, it actually checks whether the parameter implements `ICollection<T>` (which arrays do), and, if so, returns `Count` directly. Therefore, calling `.Count()` on an array isn't much slower than `.Length`, although it will involve an extra typecast.

Problem

Possible Duplicate: count vs length vs size in a collection Array.Length vs Array.Count I declared this array: ``` int[] misInts = new Int[someNumber]; /* make some happy operations with the elements in misInts */ ``` So I can get the value of SomeNumber with: misInts.Length or misInts.Count() Arrays in C# inherit from IEnumerable. So if I have: ``` Func<int> misIntsF = Enumerable.Range(0, someNumber).Select(c=> /* make some happy operations that return Integers */); ``` I am told that if I make misIntsF.Count() I actually execute the code in the Lambda expression, get the results and count them. But the array misInts doesn't have a Lambda expressión. Is misInts.Count() more memory consuming than misInts.Length? What are the differences between misInts.Count() and misInts.Length?

Original source

Related problems