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
If your concern is iterating through all of the elements in a large collection, you're okay - Any
and All
will short-circuit as soon as possible.
The statement
mySequence.Any (item => item.SomeStatus == SomeConst)
will return true as soon as one element that meets the condition is found, and
!mySequence.All (item => item.SomeStatus == SomeConst)
will return true as soon as one element does not.
Since both conditions are mutually exclusive, one of the statements is guaranteed to return after the first element, and the other is guaranteed to return as soon as the first element is found.
As pointed out by others, this solution requires starting to iterate through the collection twice. If obtaining the collection is expensive (such as in database access) or iterating over the collection does not produce the same result every time, this is not a suitable solution.