开发者

C#: Counting iEnumerable object

I am trying to get the count of the elements stored in a Ienumerable object. There is no count property for this so 开发者_运维问答how do i get the count for the var object?

Thanks


You could use the Count() extension method starting from .NET 3.5:

IEnumerable<Foo> foos = ...
int numberOfFoos = foos.Count();

Make sure you've brought it into scope by:

using System.Linq;

And don't worry about performance, the Count() extension method is intelligent enough not to loop through the enumerable if the actual type is for example a static array or a list in which case it would directly use the underlying Length or Count property.


You cannot do anything with an IEnumerable other than iterate over it.

So, to get the count, you would have to write this code:

int count = 0;
foreach(var item in enumerable) {
    ++count;
}

// Now count has the correct value

To save you the awkwardness, LINQ provides the Count extension method which does just that. You will need to do using System.Linq to use it.

Also, be aware that, depending on the nature of the IEnumerable, it might not be possible to iterate over it more than once (although this is admittedly a rare case). If you have such an object in your hands, counting the number of items will effectively render it useless for future work.


It is better to call ToList first if you finally want to convert it to a list. Especially when your lambada expression binds an outer variable:

string str = "A,B,C";
int i = 0;
var result= str.Split(',').Select(x=>x+(i++).ToString());


var count = result.Count();
var list =result.ToList();

//Now list content is A3 B4 C5, obviously not you want.


You should use the Count() method. Enumerables have no Count property.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜