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

前端 未结 1 1780
失恋的感觉
失恋的感觉 2021-01-13 21:02

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 pr

1条回答
  •  花落未央
    2021-01-13 21:47

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

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

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

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

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

    0 讨论(0)
提交回复
热议问题