Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I get the length of an IEnumerable? [duplicate]

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++;
}
like image 623
Evorlor Avatar asked May 21 '18 11:05

Evorlor


People also ask

How do you measure length of IEnumerable?

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.

How do you get the count of an IEnumerable?

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.

What does count () do in C#?

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.

Is IEnumerable fast?

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.


1 Answers

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.

like image 156
Christos Avatar answered Sep 29 '22 15:09

Christos