如何在Linq中获得左外连接?

时间:2012-04-05 09:24:12

标签: c# .net linq linq-to-sql

我的数据库中有两个表格如下:

客户:

C_ID  city
--------------
1     Dhaka
2     New york
3     London

的personal_info:

P_ID  C_ID  Field       value
-------------------------------
1     1     First Name  Nasir
2     1     Last Name   Uddin
3     2     First Name  Jon
4     3     First Name  Lee


我需要一个像这样的选择结果:

C_ID ='1':

C_ID  Name (First Name + Last Name)  City
------------------------------------------
1     Nasir Uddin                    Dhaka

C_ID ='2':

C_ID  Name (First Name + Last Name)  City
---------------------------------------------
2     Jon                            New york

相应的Linq查询将如何显示?

感谢
Nahid

1 个答案:

答案 0 :(得分:3)

按照Linq to Sql: Multiple left outer joins之前的答案,您可以看到解决此问题的结构,例如:

var result = from customer in customers  
                   from personalFirst in personal  
                       .Where(pf => pf.Field == "First Name" && pf.C_ID == customer.C_ID)  
                       .DefaultIfEmpty() 
                   from personalLast in personal  
                       .Where(pl => pl.Field == "Last Name" && pl.C_ID == customer.C_ID)  
                       .DefaultIfEmpty()  
                    where customer.C_ID == 2  
                    select new { customer.C_ID, Name = (personalFirst != null ? personalFirst.Value : "") + " " + (personalLast != null ? personalLast.Value : "") };  

显然,如果您想要所有记录,请删除对C_ID = 2

的限制