Have you ever needed to check - in a LINQ context, or otherwise - whether an IEnumerable<T> (or plain IEnumerable) contained any elements?
Of course a check using the Count<T>() extension method to check for an element count of zero works here, but this would be... unfortunate... for sequences yielding large numbers of elements because of the O(n) linear behavior.
Maybe the following source code (or the LINQ Any() method, see comments) could be of use to you in those cases from now on:
/// <summary>Sequence contains at least 1 item?</summary>
/// <typeparam name="T">Type of elements</typeparam>
/// <param name="sequence">Sequence to check</param>
/// <returns>true/false</returns>
public static bool NotEmpty<T>(this IEnumerable<T> sequence)
{
return sequence.GetEnumerator().MoveNext();
}
/// <summary>Sequence contains at least 1 item?</summary>
/// <param name="sequence">Sequence to check</param>
/// <returns>true/false</returns>
public static bool NotEmpty(this IEnumerable sequence)
{
return sequence.GetEnumerator().MoveNext();
}
These extension methods check whether the given sequence contains elements or not, but does so taking only O(1) constant time. In other words: the entire sequence is not fully evaluated, but the minimal work is being done to check if the sequence contains at least one element.