What's the "best" (taking both speed and readability into account) way to determine if a list is empty? Even if the list is of type IEnumerable<T> and doesn't have a Count property.
Right now I'm tossing up between this:
if (myList.Count() == 0) { ... }
and this:
if (!myList.Any()) { ... }
My guess is that the second option is faster, since it'll come back with a result as soon as it sees the first item, whereas the second option (for an IEnumerable) will need to visit every item to return the count.
That being said, does the second option look as readable to you? Which would you prefer? Or can you think of a better way to test for an empty list?
isandcastbut useasandnullcheck:ICollection<T> collection = list as ICollection<T>; if (collection != null) return colllection.Count;list.Any()equivalent tolist.IsEmpty? The framework method should be optimized -- it's worth writing a new one only if you figured out it's a perf bottleneck.IsEmptyextension method. github.com/dotnet/corefx/issues/35054 Please check and vote it if you like and agree.