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.
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.
IEnumerable doesn't have a Count method.
enumerable. Any() is the cleanest way to check if there are any items in the list.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With