有没有更好的调用LINQ Any + NOT All的方法? [英] Is there a better way of calling LINQ Any + NOT All?
本文介绍了有没有更好的调用LINQ Any + NOT All的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要检查序列中是否有满足某些条件的项目,但同时不是所有满足相同条件的项目.
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.
例如,对于一个包含10个项目的序列,如果该序列中至少有一个满足条件但不是全部都满足,则我希望为TRUE:
For example, for a sequence of 10 items I want to have TRUE if the sequence has at least one that satisfy the condition but not all:
- 满意的10个项目,不满意的0个,结果为FALSE
- 0个项目满意,10个项目不满意,结果为FALSE
- 满足1个项目,不满足9个项目,结果为TRUE
- 满足9个条件,不满足1个条件,结果为真
我知道我可以做到:
mySequence.Any (item => item.SomeStatus == SomeConst) && !mySequence.All (item => item.SomeStatus == SomeConst)
但这不是最佳选择.
有更好的方法吗?
推荐答案
您会喜欢的.
var anyButNotAll = mySequence
.Select(item => item.SomeStatus == SomeConst)
.Distinct()
.Take(2)
.Count() == 2;
Take(2)
停止迭代超出其必需数量的所有元素.
The Take(2)
stops it iterating over any more elements than it has to.
这篇关于有没有更好的调用LINQ Any + NOT All的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文