gpt4 book ai didi

c# - LInq left join with multiple condition in on 子句

转载 作者:太空宇宙 更新时间:2023-11-03 21:12:14 25 4
gpt4 key购买 nike

我在 SQL 中有一个连接,我需要在 linq 中编写它,这里是 select 语句:

select * from products p
left join customer cust
on((cust.identifier = p.orgID or cust.identifier = p.personalno) and cust.identifier is not null);

如何在 linq 中编写此语句?

最佳答案

  • 如果你真的想用JOIN来做,你可以这样做:

    from cust in customer
    join _p1 in products on cust.identifier equals _p1.orgID into _p1
    from p1 in _p1.DefaultIfEmpty()
    join _p2 in products on cust.identifier equals _p2.personalno into _p2
    from p2 in _p2.DefaultIfEmpty()
    where cust.identifier != null
    && (p1 != null || p2 != null)
    select new { Customer = cust, Product = p1 == null ? p2 : p1 }
  • 没有 JOIN 关键字的更简单的解决方案是:

    from p in products
    from cust.Where(q => q.identifier != null && (p.orgID == q.identifier || p.personalno == q.identifier)).DefaultIfEmpty()
    where cust != null
    select new { Product = p, Customer = cust }
  • 要回答标题建议的问题,请执行以下操作以在多个条件下进行连接,但请注意,这仅适用于 AND 条件,不适用于 OR 条件:

    from t1 in Table1
    join t2 in Table2 on new { Criteria1 = t1.criteria1, Criteria2 = t1.criteria2 } equals new { Criteria1 = t2.criteria1, Criteria2 = t2.criteria2 }
    select new { T1 = t1, T2 = t2 }

关于c# - LInq left join with multiple condition in on 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36908786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com