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

sebagomez picture sebagomez · Oct 3, 2008 · Viewed 390.7k times · Source
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.

Answer

Mendelt picture Mendelt · Oct 3, 2008

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.