hWorld
hWorld

Reputation: 185

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

Upvotes: 3

Views: 14815

Answers (4)

Zebi
Zebi

Reputation: 8882

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

Upvotes: 0

Liang
Liang

Reputation: 937

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.

Upvotes: 0

Jon
Jon

Reputation: 437336

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.

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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.

Upvotes: 14

Related Questions