Linq中最高效的书写方式是:
return enumerable.Count() > x;
我至少正在寻找以下解决方案:
请注意,enumerable.Any()
大于0的效果确实很好,但是我正在寻找一种解决方案,它可以检查大于x
。
例:
考虑使用构建的一个非常大的可枚举对象yield return
。
没有内置的LINQ方法可以提供最有效的解决方案。基本上,您需要检查是否IEnumerable<T>
具有Count属性(通过ICollection<T>
),如果没有枚举它。
public static class MoreEnumerable
{
public static bool HasAtLeast<T>(this IEnumerable<T> source, int count)
{
if (source is ICollection<T>)
{
return ((ICollection<T>)source).Count > count;
}
else if (source is ICollection)
{
return ((ICollection)source).Count > count;
}
return source.Skip(count).Any();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句