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

岁酱吖の 提交于 2019-12-12 12:33:50

问题


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.



来源:https://stackoverflow.com/questions/50448298/how-should-i-get-the-length-of-an-ienumerable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!