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?
array.Count()is actually a call to theEnumerable.Count<T>(IEnumerable<T>)extension method.Since this method takes an
IEnumerable<T>(as opposed toICollection<T>, which has aCountproperty), 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, returnsCountdirectly.Therefore, calling
.Count()on an array isn’t much slower than.Length, although it will involve an extra typecast.