leora
leora

Reputation: 196741

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

i know everyone says to avoid doing something like this because its very slow (just to find out if there is 0)

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

but what is the best alternative when all i need to do is find out if the list has a count of 0 or if there are items in it

Upvotes: 4

Views: 4353

Answers (3)

hIpPy
hIpPy

Reputation: 5125

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();
}

Upvotes: 0

David Yaw
David Yaw

Reputation: 27874

Something like this should work for you:

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

Just start enumerating, and if you can move onto the first item, it's not empty. Also, you can check if the IEnumerable also implements ICollection, and if so, call its .Count property.

Upvotes: 0

Femaref
Femaref

Reputation: 61477

Use list.Any(). It returns true if it finds an element. Implementation wise, it would be:

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

Upvotes: 11

Related Questions