I need to check if a sequence has any items satisfying some condition but at the same time NOT all items satisfying the same condition.
For example, for a sequence of 10
You could define your own extension method. This version is more verbose, but still readable, and it only enumerates the IEnumerable
once:
bool AnyButNotAll(this IEnumerable sequence, Func predicate)
{
bool seenTrue = false;
bool seenFalse = false;
foreach (ItemT item in sequence)
{
bool predResult = predicate(item);
if (predResult)
seenTrue = true;
if (!predResult)
seenFalse = true;
if (seenTrue && seenFalse)
return true;
}
return false;
}
Much shorter, but enumerates the IEnumerable
twice:
bool AnyButNotAll(this IEnumerable sequence, Func predicate)
{
return sequence.Any(predicate) && !sequence.All(predicate);
}