是否有 Linq 方法来检查集合是否至少包含 x 个项目?.Any()
很棒,因为一旦找到一个项目,它就是真的,并且程序不需要去获取集合中可能存在的任何其他内容。
有没有ContainsAtLeast()
方法 - 或者如何实现它的行为.Any()
?
我要求的是这样的行为.Any()
所以我可以避免使用.Count()
and do .AtLeast(4)
,因此如果找到 4 个项目,则返回 true。
您可以致电Skip求最小数减1,然后检查是否还有剩余:
public static bool AtLeast(this IEnumerable<T> source, int minCount)
{
return source.Skip(minCount - 1).Any();
}
请注意,对于大量数据,如果您的源实现ICollection<T>
,这可能比使用慢得多Count
。所以你可能想要:
public static bool AtLeast(this IEnumerable<T> source, int minCount)
{
var collection = source as ICollection<T>;
return collection == null
? source.Skip(minCount - 1).Any() : collection.Count >= minCount;
}
(您可能需要检查非通用ICollection
too.)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)