Search code examples
c#.netlinqcollections

Interview Question: .Any() vs if (.Length > 0) for testing if a collection has elements


In a recent interview I was asked what the difference between .Any() and .Length > 0 was and why I would use either when testing to see if a collection had elements.

This threw me a little as it seems a little obvious but feel I may be missing something.

I suggested that you use .Length when you simply need to know that a collection has elements and .Any() when you wish to filter the results.

Presumably .Any() takes a performance hit too as it has to do a loop / query internally.


Solution

  • Length only exists for some collection types such as Array.

    Any is an extension method that can be used with any collection that implements IEnumerable<T>.

    If Length is present then you can use it, otherwise use Any.


    Presumably .Any() takes a performance hit too as it has to do a loop / query internally.

    Enumerable.Any does not loop. It fetches an iterator and checks if MoveNext returns true. Here is the source code from .NET Reflector.

    public static bool Any<TSource>(this IEnumerable<TSource> source)
    {
        if (source == null)
        {
            throw Error.ArgumentNull("source");
        }
        using (IEnumerator<TSource> enumerator = source.GetEnumerator())
        {
            if (enumerator.MoveNext())
            {
                return true;
            }
        }
        return false;
    }