在Linq加入条件

时间:2015-08-19 10:08:30

标签: c# linq

我需要将以下SQL转换为LINQ:

Select Person.*, Governorate.OptionName
from Person 
Left Join Option Governorate on Governorate.OptionListName='Governorate' 
and Person.GovernorateId=Governorate.GovernorateId

我做了以下事情:

from person in db.persons
join governorate in db.Options 
on  new { Key1=person.GovernorateId,
         Key2=true} equals
    new { Key1=governorate.OptionValue,
         Key2= governorate.OptionListName equals "Governorate"}
select person, governorate

但这会产生两个错误:
1-对于:Key2= governorate.OptionListName equals "Governorate"     为“省”声明的equals和Anonymus类型的语法错误

2- For:select person, governorate 省不能在这个范围内宣布,因为它会赋予省不同的意义。

3 个答案:

答案 0 :(得分:2)

from person in db.persons
   join governorate in db.Options 
       on  new { Key1=person.GovernorateId, Key2="Governorate"} equals
new { Key1=governorate.OptionValue, Key2= governorate.OptionListName  }
into g
select new {
             person = person, 
             governorates = g
           }

它为您提供了一组对象,每个对象都有一个person和一个与governorate对应的集合。

如果您希望结果包含persongovernorate

from person in db.persons
   join governorate in db.Options 
       on  new { Key1=person.GovernorateId, Key2="Governorate"} equals
new { Key1=governorate.OptionValue, Key2= governorate.OptionListName  }
into groups
from g in groups.DefaultIfEmpty()
select new {
             person = person, 
             governorates = g.OptionName
           }

这将返回一个对象集合,每个对象包含一对persongovernorate.OptionName

来自MSDN

的第二个查询的一些解释
  

生成两个集合的左外连接的第一步是使用组连接执行内连接   第二步是将第一个(左)集合的每个元素包含在结果集中,即使该元素在右集合中没有匹配项也是如此。这是通过在组连接的每个匹配元素序列上调用DefaultIfEmpty 来实现的。

答案 1 :(得分:1)

from person in db.persons
join governorate in db.Options 
on   person.GovernorateId equals governorate.OptionValue  
where governorate.OptionListName =="Governorate"       
select person, governorate

OR 你可以试试这个

from person in db.persons
join governorate in db.Options.Where(x=>x.OptionListName =="Governorate") 
on   person.GovernorateId equals governorate.OptionValue 
select person, governorate

例如:我试过这个并且效果很好。

from u in User_Accounts.Where(x=>x.User_Account_Type =="Client")
join a in Clients on u.Client_ID equals a.Client_ID
select u

答案 2 :(得分:1)

from p in db.persons
join h in db.Options on p.GovernorateId equals h.OptionValue && h.OptionListName equals "Governorate" into t
 from rt in t

 select new
 {
       p.person, h.governorate
 }).ToList();