C# LINQ 与 OR 连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1159022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LINQ join with OR
提问by AndyMcKenna
I want to do a JOIN with LINQ using an OR statement.
我想使用 OR 语句与 LINQ 进行 JOIN。
Here is the SQL query I'm starting with:
这是我开始的 SQL 查询:
SELECT t.id
FROM Teams t
INNER JOIN Games g
ON (g.homeTeamId = t.id OR g.awayTeamId = t.id)
AND g.winningTeamId != 0
AND g.year = @year
GROUP BY t.id
I'm having trouble converting that ON clause to LINQ. This is where I'm at:
我无法将该 ON 子句转换为 LINQ。这是我所在的位置:
var y = from t in db.Teams
join g in db.Games on t.ID equals g.AwayTeamID //missing HomeTeamID join
where g.WinningTeamID != 0
&& g.Year == year
group t by t.ID into grouping
select grouping;
I think I could use:
我想我可以使用:
join g in db.Games on 1 equals 1
where (t.ID == g.HomeTeamID || t.ID == g.AwayTeamID)
and this works but seems kind of seems hacky. Is there a better way?
这有效,但似乎有点像hacky。有没有更好的办法?
采纳答案by Amit G
The where clause applies a boolean condition, so using "||" is the way to go. You can chain multiple where clauses but I believe that will give you a "and" operation, rather than an "or".
where 子句应用布尔条件,因此使用“||” 是要走的路。您可以链接多个 where 子句,但我相信这会给您一个“和”操作,而不是“或”。
回答by ammills01
I struggled with this as well until I found the following solution, which worked well for my situation:
我也为此苦苦挣扎,直到找到以下解决方案,这对我的情况很有效:
var y = from t in db.Teams
from g in db.Games
where
(
t.ID == g.AwayTeamID
|| t.ID == g.HomeTeamID
)
&& g.WinningTeamID != 0
&& g.Year == year
group t by t.ID into grouping
select grouping;
Under the covers, your solution probably works very close to this one. However, I bet this one is just a bit faster if you benchmark it since it is not JOINING every item in the first dataset with every item in the second dataset, which could be a disaster if either (or both) dataset were really big.
在幕后,您的解决方案可能与此解决方案非常接近。但是,我敢打赌,如果您对它进行基准测试,它会快一点,因为它不会将第一个数据集中的每个项目与第二个数据集中的每个项目连接起来,如果其中一个(或两个)数据集非常大,这可能是一场灾难。