Given an initialised IEnumerable
:
IEnumerable<T> enumerable;
I would like to determine if it has more than one element. I think the most obvious way to do this is:
enumerable.Count() > 1
However, I believe Count()
enumerates the whole collection, which is unnecessary for this use case. For example, if the collection contains a very large amount of elements or provided its data from an external source, this could be quite wasteful in terms of performance.
How can I do this without enumerating any more than 2 elements?
enumerable. Any() is the cleanest way to check if there are any items in the list.
IEnumerable is conceptually faster than List because of the deferred execution. Deferred execution makes IEnumerable faster because it only gets the data when needed. Contrary to Lists having the data in-memory all the time.
You can test this in many ways by combining the extension methods in System.Linq... Two simple examples are below:
bool twoOrMore = enumerable.Skip(1).Any(); bool twoOrMoreOther = enumerable.Take(2).Count() == 2;
I prefer the first one since a common way to check whether Count() >= 1
is with Any()
and therefore I find it more readable.
For the fun of it, call Next() twice, then get another IEnumerable.
Or, write a small wrapper class for this specific goal: EnumerablePrefetcher : IEnumerable<T>
to try and fetch the specified amount of items upon initialization.
Its IEnumerable<T> GetItems()
method should use yield return in this fashion
foreach (T item in prefetchedItems) // array of T, prefetched and decided if IEnumerable has at least n elements { yield return item; } foreach (T item in otherItems) // IEnumerable<T> { yield return item; }
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