Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq equivalent for collection contains at least x items; like .Any() but instead .AtLeast(int)

Tags:

c#

linq

Is there a Linq method to check whether a collection contains at least x items? .Any() is great because as soon as one item is found, it will be true and the program won't need to go and get whatever else might be in the collection. Is there a ContainsAtLeast() method - or how could one implement it to behave like .Any()?

What I'm asking for is behavior like .Any() so I can avoid using .Count() and do .AtLeast(4), so if it finds 4 items, it returns true.

like image 743
Matt Avatar asked Dec 20 '22 00:12

Matt


1 Answers

You can call Skip for the minimum number minus 1, and then check if there are any left:

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

Note that for large counts, if your source implements ICollection<T>, this could be significantly slower than using Count. So you might want:

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;
}

(You might want to check for the non-generic ICollection too.)

like image 130
Jon Skeet Avatar answered Dec 28 '22 22:12

Jon Skeet