Quite often I find myself wanting to check in a petite way if an enumerable is empty. Instead of having to do:
bool notEmpty = myEnumerable.GetEnumerator().MoveNext();
Using linq you can simply use this System.Linq.Any() extension method:
var notEmpty = myEnumerable.Any();
I´m often afraid to overuse linq since some of the commands could end up iterating the entire enumerable to get your results, like writing:
bool isEmpty = myEnumerable.ToArray().Length == 0;
The above could definitely give a performance hit if placed in an unfortunate codeblock.
However, reflecting the Any() method gives us:
public static bool Any (this IEnumerable source) {
if (source == null) {
throw Error.ArgumentNull ("source");
} else {
using (IEnumerator enumerator = source.GetEnumerator ()) {
if (enumerator.MoveNext ())
return true;
}
return false;
}
}
In other words, it just compresses the first codeblock I used in a neat and understandable manner.
Enumerate away!