集合的Linq等价物至少包含x个项目; 比如.Any()而是.AtLeast(int)

Mat*_*att 4 c# linq

是否有Linq方法来检查集合是否包含至少x个项目? .Any()很棒,因为一旦找到一个项目,它就会成立,程序将不需要去获取集合中的任何其他内容.有没有一种ContainsAtLeast()方法 - 或者如何实现它的行为.Any()

我要求的是行为,.Any()所以我可以避免使用.Count()和做.AtLeast(4),所以如果它找到4项,它返回true.

Jon*_*eet 11

您可以拨打Skip最小号码减去1,然后检查是否有剩余号码:

public static bool AtLeast(this IEnumerable<T> source, int minCount)
{
    return source.Skip(minCount - 1).Any();
}
Run Code Online (Sandbox Code Playgroud)

请注意,对于大数量,如果您的源实现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;
}
Run Code Online (Sandbox Code Playgroud)

(您可能也想检查非泛型ICollection.)