I was writing some code, and went to get the length of an IEnumerable. When I wrote myEnumerable.Count()
, to my surprise, it did not compile. After reading Difference between IEnumerable Count() and Length, I realized that it was actually Linq that was giving me the extension method.
Using .Length does not compile for me either. I am on an older version of C#, so perhaps that is why.
What is the best practice for getting the length of an IEnumerable? Should I use Linq's Count() method? Or is there a better approach. Does .Length become available on a later version of C#?
Or if I need the count, is an IEnumerable the wrong tool for the job? Should I be using ICollection instead? Count the items from a IEnumerable<T> without iterating? says that ICollection is a solution, but is it the right solution if you want an IEnumerable with a count?
Obligatory code snippet:
var myEnumerable = IEnumerable<Foo>();
int count1 = myEnumerable.Length; //Does not compile
int count2 = myEnumerable.Count(); //Requires Linq namespace
int count3 = 0; //I hope not
for(var enumeration in myEnumerable)
{
count3++;
}
If you need to read the number of items in an IEnumerable<T> you have to call the extension method Count , which in general (look at Matthew comment) would internally iterate through the elements of the sequence and it will return you the number of items in the sequence. There isn't any other more immediate way.
Simplifying all answer. 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. Save this answer.
To count the number of elements in the C# array, we can use the count() method from the IEnumerable. It is included in the System.
IEnumerable is conceptually faster than List because of the deferred execution. Deferred execution makes IEnumerable faster because it only gets the data when needed. Contrary to Lists having the data in-memory all the time.
If you need to read the number of items in an IEnumerable<T>
you have to call the extension method Count
, which in general (look at Matthew comment) would internally iterate through the elements of the sequence and it will return you the number of items in the sequence. There isn't any other more immediate way.
If you know that your sequence is an array, you could cast it and read the number of items using the Length
property.
No, in later versions there isn't any such method.
For implementation details of Count
method, please have a look at here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With