linq to sql: join multiple columns from the same table

前端 未结 5 1794
有刺的猬
有刺的猬 2020-12-06 00:58

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 tab         


        
相关标签:
5条回答
  • 2020-12-06 01:29
    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.

    0 讨论(0)
  • 2020-12-06 01:30

    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
    
    0 讨论(0)
  • 2020-12-06 01:34

    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;
    
    0 讨论(0)
  • 2020-12-06 01:41

    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}
              ...
    
    0 讨论(0)
  • 2020-12-06 01:41

    In VB:

     dim qry = FROM t1 in table1 _
               JOIN t2 in table2 on t2.ID equals t1.ID _
               AND t2.Country equals t1.Country 
    
    0 讨论(0)
提交回复
热议问题