What is the fastest way to check for IEnumerable Count is greater than zero without a loop through all records

I know that everyone says not to do something like that, because it is very slow (just to find out if there are 0)

IEnumerable<MyObject> list; if (list.Count() > 0) { } 

but what is the best alternative when all I have to do is find out if the list has 0 or if there are elements in it

+4
source share
3 answers

Use list.Any() . It returns true if it finds an element. The implementation is wise, this would be:

 using (var enumerator = list.GetEnumerator()) { return enumerator.MoveNext(); } 
+11
source

Something like this should work for you:

 public static IsEmpty(this IEnumerable list) { IEnumerator en = list.GetEnumerator(); return !en.MoveNext(); } 

Just start the listing, and if you can go to the first element, it will not be empty. Alternatively, you can check if IEnumerable implements ICollection, and if so, call its .Count property.

0
source

Also check for null and count as if (!list.IsNullOrEmpty()) { ... }

 /// <summary> /// Returns true if collection is null or empty. /// </summary> public static bool IsNullOrEmpty<T>(this IEnumerable<T> source) { return source == null || !source.Any(); } 
0
source

All Articles