假设我想检查集合中是否至少有 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;
}
最佳答案
.Count()
方法中内置了一些有据可查的优化。具体来说,如果您的枚举是 ICollection
,.Count()
将是一个恒定时间操作,因为它将使用 ICollection
的 .Count
属性。
但是,在一般情况下,它将迭代整个 IEnumerable
以获取计数。如果您没有 ICollection
,当元素超过 N 个时,最好使用您推荐的两种方法中的任何一种。对于这两者的相对性能,您必须按照其他人的建议对它们进行分析。
关于c# - LINQ Count() until,这样效率更高吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9627666/