MoreLINQ icon indicating copy to clipboard operation
MoreLINQ copied to clipboard

`All` overload (or `AnyAndAll`) that returns `false` if sequence is empty

Open jibbers42 opened this issue 3 years ago • 1 comments

Inspired by https://stackoverflow.com/a/34981556, a method like this would be convenient...

static bool All<T>(this IEnumerable<T> source, Func<T, bool> predicate, bool mustHaveItems)
{
    foreach (var e in source)
    {
        if (!predicate(e))
            return false;
        mustHaveItems= false;
    }
    return !mustHaveItems;
}

Elsewhere in the thread a similar method named AnyAndAll was suggested. I'd probably prefer this I guess, simply because the call site would read cleaner...

static bool AnyAndAll<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
    bool isEmpty = true;
    foreach (var e in source)
    {
        if (!predicate(e))
            return false;
        isEmpty = false;
    }
    return !isEmpty;
}

jibbers42 avatar Jun 03 '22 21:06 jibbers42

This can be implemented trivially by combining existing operators:

public static bool AnyAndAll<T>(this IEnumerable<T> source, Func<T, bool> predicate) =>
    source.Select(predicate).DefaultIfEmpty(false).All(f => f);

atifaziz avatar Jan 12 '23 22:01 atifaziz