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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With