sebagomez sebagomez - 1 year ago 89
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download