Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
jibbers42 opened this issue Jun 3, 2022 · 1 comment
Open

Comments

@jibbers42
Copy link

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;
}
@atifaziz atifaziz changed the title All overload (or AnyAndAll) that returns false if Enumerable is empty All overload (or AnyAndAll) that returns false if sequence is empty Jan 12, 2023
@atifaziz
Copy link
Member

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants