Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to do a JOIN with LINQ using an OR statement.

Here is the SQL query I'm starting with:

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:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
148 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...