在JOIN子句中使用OR条件进行LINQ查询 [英] LINQ Query Using OR Condition in JOIN Clause
问题描述
注意: C#或VB.NET的答案都可以,但是我的问题将在VB.NET中...
我一直在尝试将以下SQL转换为LINQ to Entity语句:
Note: C# or VB.NET answers are fine, but my question will be in VB.NET...
I have been trying to convert the following SQL into a LINQ to Entity statement:
SELECT
*
FROM Person
JOIN Company
ON Person.CompanyName = Company.CompanyName
OR
(
Person.CompanyName = 'Unemployed'
AND Company.VolunteerJob = 1
)
但是,LINQ似乎在JOIN子句中不支持OR运算符.我的一位同事建议我使用UNION,我明天将尝试使用UNION,但我想知道是否还有更明显的语法.为了澄清,这就是我要做的(语法不支持此操作):
However, LINQ does not seem to support the OR operator in JOIN clauses. A coworker of mine helpfully suggested I use a UNION, which I will try tomorrow, but I''d like to know if there is a more obvious syntax. To clarify, this is what I am trying to do (the syntax does not support this):
Dim results =
From Person In context.Person
Join Company In context.Company
On Person.CompanyName Equals Company.CompanyName Or
(Person.CompanyName Equals "Unemployed" And Company.VolunteerJob = 1)
请注意,我真正使用的表/字段与上面的内容完全不同...我只是在上面用于演示目的.
Note that the tables/fields I am really using are nothing like the above... I am just using them above for demonstration purposes.
推荐答案
我有两种方法我正在考虑,但在决定之前我必须研究一下性能.一种方法将所有条件放在WHERE子句中,另一种方法UNION将两个初始结果集组合在一起.
There are two approaches I am considering, but I have to look into the performance before I decide. One approach puts all the conditions in the WHERE clause, and the other approach UNIONs two initial result sets.
' Get all companies in one LINQ query.
Dim combinedCompanies =
From P in context.Person
From C in context.Company
Where
C.CompanyName Equals P.CompanyName
And P.CompanyName <> "Unemployed"
Or
(
P.CompanyName = "Unemployed" And
C.VolunteerJob = True
)
这是我的同事推荐的版本:
This is the version that my coworker recommended:
' Join with normal companies.
Dim matchingCompanies =
From P In context.Person
Join C In context.Company
On C.CompanyName Equals P.CompanyName
Where
P.CompanyName <> "Unemployed"
' Join with volunteer companies.
Dim volunteerCompanies =
From P In context.Person
From C In context.Company
Where
P.CompanyName = "Unemployed" And
C.VolunteerJob = True
' Combine normal and volunteer companies.
Dim combinedCompanies = matchingCompanies.Union(volunteerCompanies)
我喜欢第一种方法的简洁性,但是我不确定它是否会像第二种方法那样高效.
I like the brevity of the first approach, but I''m not sure it will be as performant as the second approach.
尝试从这里使用LINQ pad [ ^ ]
OR写为||在LINQ
还要检查此 [
Hi,
try using LINQ pad from here[^]
OR is written as || in LINQ
also check this[^]
这篇关于在JOIN子句中使用OR条件进行LINQ查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!