Is there a better way of calling LINQ Any + NOT All?

后端 未结 8 942
走了就别回头了
走了就别回头了 2021-02-18 14:46

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

8条回答
  •  悲哀的现实
    2021-02-18 15:26

    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.

提交回复
热议问题