what is the fastest way to check IEnumerable Count is greater than zero without loop through all records
i know everyone 开发者_StackOverflow社区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
Use list.Any()
. It returns true if it finds an element. Implementation wise, it would be:
using (var enumerator = list.GetEnumerator())
{
return enumerator.MoveNext();
}
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.
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();
}
精彩评论