MoreLINQ
MoreLINQ copied to clipboard
`All` overload (or `AnyAndAll`) that returns `false` if sequence is empty
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;
}
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);