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

后端 未结 8 928
走了就别回头了
走了就别回头了 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:18

    You'll like this.

    var anyButNotAll = mySequence
        .Select(item => item.SomeStatus == SomeConst)
        .Distinct()
        .Take(2)
        .Count() == 2;
    

    The Take(2) stops it iterating over any more elements than it has to.

提交回复
热议问题