Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ join with OR

Tags:

c#

linq-to-sql

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?

like image 779
AndyMcKenna Avatar asked Jul 21 '09 12:07

AndyMcKenna


People also ask

Is LINQ join inner or outer?

When you use the LINQ join clause in the query expression syntax to combine two sets of related information, you perform an inner join. This means that you provide an expression that determines for each item in the first sequence, the matching items in the second.

Can we use join in LINQ?

LINQ Join queries. As we know the JOIN clause is very useful when merging more than two table or object data into a single unit. It combines different source elements into one and also creates the relationship between them. Using the join, you can grab the data based on your conditions.

What type of join is LINQ join?

In LINQ, an inner join is used to serve a result which contains only those elements from the first data source that appears only one time in the second data source. And if an element of the first data source does not have matching elements, then it will not appear in the result data set.

How does LINQ join work?

In a LINQ query expression, join operations are performed on object collections. Object collections cannot be "joined" in exactly the same way as two relational tables. In LINQ, explicit join clauses are only required when two source sequences are not tied by any relationship.


1 Answers

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.

like image 81
ammills01 Avatar answered Oct 23 '22 18:10

ammills01