Reputation: 196741
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
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
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
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