集合的Linq等价物至少包含x个项目; 比如.Any()而是.AtLeast(int)
是否有Linq方法来检查集合是否包含至少x个项目? .Any()
很棒,因为一旦找到一个项目,它就会成立,并且程序将不需要去获取集合中可能存在的任何其他内容。 是否有ContainsAtLeast()
方法 – 或者如何实现它的行为类似.Any()
?
我要求的是像.Any()
这样的行为,所以我可以避免使用.Count()
并执行.AtLeast(4)
,所以如果它找到4个项目,则返回true。
你可以调用Skip
最小数字减1,然后检查是否有任何左边:
public static bool AtLeast(this IEnumerable source, int minCount) { return source.Skip(minCount - 1).Any(); }
请注意,对于大型计数,如果您的源实现ICollection
,这可能比使用Count
慢得多。 所以你可能想要:
public static bool AtLeast(this IEnumerable source, int minCount) { var collection = source as ICollection ; return collection == null ? source.Skip(minCount - 1).Any() : collection.Count >= minCount; }
(您可能也想检查非genericsICollection
。)