Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

private IEnumerable<string> Tables {     get     {         yield return "Foo";         yield return "Bar";     } } 

Let's say I want iterate on those and write something like processing #n of #m.

Is there a way I can find out the value of m without iterating before my main iteration?

I hope I made myself clear.

like image 756
sebagomez Avatar asked Oct 03 '08 21:10

sebagomez


People also ask

How do I count items in IEnumerable?

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.

Does IEnumerable have count?

IEnumerable doesn't have a Count method.

How do I know if IEnumerable has an item?

enumerable. Any() is the cleanest way to check if there are any items in the list.

What is the difference between count and count () in C#?

So why do we care about the difference between Count and Count()? One simply reads a value in memory to determine the count of the elements in a collection and the other iterates over the entire collection in memory to determine the count of the number of items.


2 Answers

IEnumerable doesn't support this. This is by design. IEnumerable uses lazy evaluation to get the elements you ask for just before you need them.

If you want to know the number of items without iterating over them you can use ICollection<T>, it has a Count property.

like image 174
Mendelt Avatar answered Sep 24 '22 15:09

Mendelt


The System.Linq.Enumerable.Count extension method on IEnumerable<T> has the following implementation:

ICollection<T> c = source as ICollection<TSource>; if (c != null)     return c.Count;  int result = 0; using (IEnumerator<T> enumerator = source.GetEnumerator()) {     while (enumerator.MoveNext())         result++; } return result; 

So it tries to cast to ICollection<T>, which has a Count property, and uses that if possible. Otherwise it iterates.

So your best bet is to use the Count() extension method on your IEnumerable<T> object, as you will get the best performance possible that way.

like image 22
Daniel Earwicker Avatar answered Sep 24 '22 15:09

Daniel Earwicker