【问题标题】:c# Linq How to write Innter Join using if conditionc# Linq如何使用if条件编写Inner Join
【发布时间】:2020-11-18 05:19:20
【问题描述】:

我这里有两张桌子 员工

Id  IsAccepected(bool)   AccepectedBy  EmpId
1        0                  0            E1-1
2        1                  2            E1-2
3        1                  1            C1-1

登录

Id name
1  John
2  Mick
3  smith

这是我的问题,如果 IsAccepected==True 那么我需要从登录表中获取已接受记录

    var x=(from n i in _db.EMployee
WHERE n.Empid='E1-1'
           select n).Tolist();
    foreach(var item in x){
    if(item.IsAccepected==True){
    .......
    }

但我不需要所有这些,是否可以在 Linq 中编写此条件

【问题讨论】:

    标签: c# linq-to-entities


    【解决方案1】:

    我猜你需要这个 sql 查询需要在 linq 中对吗?

    select b1.*,isnull((select 1 from A as a1 where a1.AccepectedBy=b1.Id and a1.EmpId='E1-2'),0) as isaccepted from B as b1

    【讨论】:

    • var result= (从 b1 in db.B select new { id=b1.ID, name=b1.name, isAccepted=(db.A.where(l=>l.AccepectedBy== b1.ID 和 l.EmpId=="E1-2").firstorDefault())?true:false }).Tolist();
    【解决方案2】:

    类似下面的东西应该可以工作:

    var x = from e in _db.Employee join l in _db.Login on e.AcceptedBy equals l.ID where e.Accepted == true select l;
    

    【讨论】:

    • 你是对的,但我需要根据条件刚才我修改我的查询
    【解决方案3】:

    通过左连接方法使用此代码-

    select Login.name,Employee.EmpId from Employee left join Login on Employee.AccepectedBy=Login.Id where Employee.[IsAccepected(bool)]=1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-04
      • 1970-01-01
      • 2011-09-13
      • 2019-09-17
      • 2020-10-02
      • 2010-10-06
      • 2018-01-27
      • 1970-01-01
      相关资源
      最近更新 更多