×

Loading...
Ad by
  • 推荐 OXIO 加拿大高速网络,最低月费仅$40. 使用推荐码 RCR37MB 可获得一个月的免费服务
Ad by
  • 推荐 OXIO 加拿大高速网络,最低月费仅$40. 使用推荐码 RCR37MB 可获得一个月的免费服务

It should be OK to join C (and D) with A or B. Following query is only correct.

var q = from a in A
join b in B on a.ID equals b.ID
join c in C on b.ID equals c.ID into G1
from g1 in G1.DefaultIfEmpty()
join d in D on b.ID equals d.ID into G2
from g2 in G2.DefaultIfEmpty()
select new { a, b, g1, g2 };

Only thing should be careful is that join condition must be
outer parameter equals inner parameter (b.ID equals c.ID)
It cannot be written as
inner parameter equals outer parameter ((c.ID equals b.ID))
That is little bit different from SQL join query.
Report

Replies, comments and Discussions:

  • 工作学习 / 学科技术讨论 / C#问题, 如何把多个表的join转换成LINQ?
    select * from table_a A
    inner join table_b B on A.id1=B.id1 and A.id2=B.id2
    left join table_c C on A.id1=C.id1 and A.id2=C.id2
    left join table_d D on B.id1=D.id1 and B.id2=D.id2

    哪位大侠帮忙写成LINQ?
    • Here is a link explain how to do left and right join. I believe it is what you are looking for.
      • 这个是2个表的join, 我说的是多个表的.
        • The easiest way is join the first 2 tables first then use the result to join the third. Before you use ToList() or getting the content It won't actually execute the query.
          So no matter how many lines of LINQ you use for this query, they will be sent to server once only before you really asking the content.

          I did not actually test this query, but for sure it will work.
    • If you don’t need filter out missing records in C and D, it’s simple.
      var q = from a in A
      join b in B on a.ID equals b.ID
      join c in C on a.ID equals c.ID into g1
      join d in D on a.ID equals d.ID into g2
      select new { a, b, g1, g2 };
      • 如果C和D都和A join, 可以通过编译. 不然, 有编译错误. Compiler Error CS1937
        • It should be OK to join C (and D) with A or B. Following query is only correct.
          var q = from a in A
          join b in B on a.ID equals b.ID
          join c in C on b.ID equals c.ID into G1
          from g1 in G1.DefaultIfEmpty()
          join d in D on b.ID equals d.ID into G2
          from g2 in G2.DefaultIfEmpty()
          select new { a, b, g1, g2 };

          Only thing should be careful is that join condition must be
          outer parameter equals inner parameter (b.ID equals c.ID)
          It cannot be written as
          inner parameter equals outer parameter ((c.ID equals b.ID))
          That is little bit different from SQL join query.