C# 貌似简单的LINQ查询让我很反感。我想要数组A中的所有项,除非它存在于数组B中
所以我有这个疑问。currentSurveyors和surveyorsInState都是相同类型的阵列。currentSurveyors可以有0个或多个项目。我想返回所有测量师状态,除非该条目在currentSurveyors中。我做错了什么C# 貌似简单的LINQ查询让我很反感。我想要数组A中的所有项,除非它存在于数组B中,c#,linq,C#,Linq,所以我有这个疑问。currentSurveyors和surveyorsInState都是相同类型的阵列。currentSurveyors可以有0个或多个项目。我想返回所有测量师状态,除非该条目在currentSurveyors中。我做错了什么 from current in currentSurveyors from surveyors in surveyorsInState where (surveyors.SurveyorID != curre
from current in currentSurveyors
from surveyors in surveyorsInState
where (surveyors.SurveyorID != current.SurveyorID ||
currentSurveyors.Count() == 0)
select surveyors;
保罗的解决方案是正确的——它应该是:
surveyorsInState.Except(currentSurveyors)
然而,值得一看原始查询失败的原因,以及它实际在做什么。这又是:
from current in currentSurveyors
from surveyors in surveyorsInState
where (surveyors.SurveyorID != current.SurveyorID ||
currentSurveyors.Count() == 0)
select surveyors;
在where
之前,考虑测量员
和当前
的值。你基本上是在做交叉连接-所以如果currentSurveyors是{a,B,C},surveyorsInState是{B,C,D},那么在得到所有这些数据之前:
current surveyors
A B
A C
A D
B B
B C
B D
C B
C C
C D
现在,对于where子句-currentSurveyors.Count()
将永远不会为零-您只是检查原始序列是否为空。事实上,您必须使用where子句,这表明情况并非如此!因此,您所要做的就是丢弃两个ID匹配的行,留下:
current surveyors
A B
A C
A D
B C
B D
C B
C D
然后您只选择了测量员,因此我们去掉了左边的列:
surveyors
B
C
D
C
D
B
D
这就是你以前看到的结果
你现在明白为什么了吗?想象一下查询中每一行的结果序列是一个好主意(这里我省略了前两行,但您不必这样做),这样您就可以跟踪正在发生的事情。我相信这是正确的
from surveyors in surveyorsInState
where !(from current in currentSurveyors select current.SurveyorID).Contains(surveyors.SurveyorID)
select surveyors;
哎哟,我打错了《你打败了我》:(+1Damn我需要打得更快。再打一次。+1我知道一定是这么简单的事情。我的大脑太兴奋了,无法思考。。。
from surveyors in surveyorsInState
where !(from current in currentSurveyors select current.SurveyorID).Contains(surveyors.SurveyorID)
select surveyors;