19

How do I inner join multiple columns from the same tables via Linq?

For example: I already have this...

join c in db.table2 on table2.ID equals table1.ID

I need to add this...

join d in db.table2 on table2.Country equals table1.Country 
OscarRyz
  • 196,001
  • 113
  • 385
  • 569
Pete Haas
  • 1,800
  • 1
  • 12
  • 15

5 Answers5

31

This is the only way I was able to get it to work (in c#).

var qry = from t1 in table1
          join t2 in table2
          on new {t1.ID,t1.Country} equals new {t2.ID,t2.Country}
          ...
Ryan Emerle
  • 15,461
  • 8
  • 52
  • 69
Pete Haas
  • 1,800
  • 1
  • 12
  • 15
15

You can put your query inside a Where clause instead of using the join operator.

The join operator supports multiple clauses in VB.NET, but not C#.

Alternatively, you can use the ANSI-82 style of 'SQL' syntax, e.g.:

from t1 in table1
from t2 in table1
where t1.x == t2.x
&& t1.y == t2.y
Rik Hemsley
  • 877
  • 1
  • 10
  • 15
  • 1
    this logical structure was deprecated in sql over nearly 20 years ago. (http://stackoverflow.com/questions/334201/why-isnt-sql-ansi-92-standard-better-adopted-over-ansi-89) Matching it in linq isn't wrong, especially in tiny queries like this, but Pete Haas's syntax is stylistically preferable – user314321 Dec 11 '15 at 15:52
13

from http://www.onedotnetway.com/linq-to-sql-join-on-multiple-conditions/

Both these tables have PostCode and CouncilCode as common fields. Lets say that we want to retrieve all records from ShoppingMall where both PostCode and CouncilCode on House match. This requires us to do a join using two columns. In LINQ such a join can be done using anonymous types. Here is an example.

var query = from s in context.ShoppingMalls
        join h in context.Houses
        on
        new { s.CouncilCode, s.PostCode }
        equals
         new { h.CouncilCode, h.PostCode }
        select s;
oglester
  • 6,605
  • 8
  • 43
  • 63
  • don't know how much Googling it took to find an example of a multiple column linq join using query syntax. Thank you. – RMuesi May 22 '13 at 23:25
6
var query = from s in context.ShoppingMalls
join h in context.Houses
on
new {CouncilCode=s.CouncilCode, PostCode=s.PostCode }
equals
new {CouncilCode=h.District, PostCode=h.ZipCode }
select s;

This is applicable for any kind of datatype.

Thiem Nguyen
  • 6,345
  • 7
  • 30
  • 50
Raj Kumar Dey
  • 61
  • 1
  • 2
1

In VB:

 dim qry = FROM t1 in table1 _
           JOIN t2 in table2 on t2.ID equals t1.ID _
           AND t2.Country equals t1.Country 
TGnat
  • 3,903
  • 8
  • 35
  • 46