Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Count() until, is this more efficient?

Say I want to check whether there are at least N elements in a collection.

Is this better than doing?

Count() >= N

Using:

    public static bool AtLeast<T>(this IEnumerable<T> enumerable, int max)
    {
        int count = 0;
        return enumerable.Any(item => ++count >= max);
    }

Or even

    public static bool Equals<T>(this IEnumerable<T> enumerable, int amount)
    {
        return enumerable.Take(amount).Count() == amount;
    }

How could I benchmark this?

    /// <summary>
    /// Returns whether the enumerable has at least the provided amount of elements.
    /// </summary>
    public static bool HasAtLeast<T>(this IEnumerable<T> enumerable, int amount)
    {
        return enumerable.Take(amount).Count() == amount;
    }

    /// <summary>
    /// Returns whether the enumerable has at most the provided amount of elements.
    /// </summary>
    public static bool HasAtMost<T>(this IEnumerable<T> enumerable, int amount)
    {
        return enumerable.Take(amount + 1).Count() <= amount;
    }
like image 358
bevacqua Avatar asked Mar 09 '12 01:03

bevacqua


1 Answers

There are some well-documented optimizations built in to the .Count() method. Specifically, if your enumerable is an ICollection, .Count() will be a constant-time operation as it will use the ICollection's .Count property.

However, in the general case it will iterate the entire IEnumerable to get the count. If you do not have an ICollection, you'd be better off using either of your two suggested methods when there are more than N elements. For the relative performance of those two, you'd have to profile them as others have suggested.

like image 140
goric Avatar answered Oct 11 '22 11:10

goric