sebagomez sebagomez - 1 month ago 6
C# Question

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

private IEnumerable<string> Tables
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.


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 IList<T>, it has a Count property.