How should I get the length of an IEnumerable? [du

2019-07-15 08:12发布

问题:

This question already has an answer here:

  • Count the items from a IEnumerable<T> without iterating? 19 answers

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++;
}

回答1:

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 them number of items using th Length property.

No, in later versions there isn't any such method.

For implementation details of Count method, please have a look at here.