【发布时间】:2012-03-09 01:21:01
【问题描述】:
假设我想检查一个集合中是否至少有 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;
}
【问题讨论】:
-
我如何对此进行基准测试? - 将您通常用来调用它们的代码放入一个带计时的循环中......
-
另一个选项:enumerable.Select((o, idx) => idx).Any(i => i >= max);
标签: c# performance linq ienumerable micro-optimization