假设我想要检查一个集合中是否至少有N个元素。
这个比使用以下代码会更好吗?
Count() >= N
使用:
public static bool AtLeast<T>(this IEnumerable<T> enumerable, int max)
{
int count = 0;
return enumerable.Any(item => ++count >= max);
}
甚至可以这样做
public static bool Equals<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.Take(amount).Count() == amount;
}
我该如何对此进行基准测试?
/// <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;
}