Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I efficiently determine if an IEnumerable has more than one element?

Tags:

c#

vb.net

linq

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?

like image 489
Sam Avatar asked Jun 24 '13 23:06

Sam


People also ask

How do I know if IEnumerable has an item?

enumerable. Any() is the cleanest way to check if there are any items in the list.

Is IEnumerable faster than list C#?

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.


2 Answers

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.

like image 76
Cameron S Avatar answered Sep 21 '22 15:09

Cameron S


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; } 
like image 40
Andrevinsky Avatar answered Sep 18 '22 15:09

Andrevinsky