linq 与 case 条件连接

2024-05-10

您好,我知道如何在使用 linq 时执行选择“case”条件吗? 注释掉的代码是我的问题。我如何将条件放在那里? 我的代码:

var r = from u in Users
    join p in Payments on u.Id equals p.UserId
    join soi in SaleOrderItems on p.ReferenceId equals soi.Id
           //if soi.InventoryTypeId == 1
              //then join i in Inventories on soi.InventoryOrCourseId equals i.Id
           //elseif soi.InventorytypeId ==2
              //then join c in Courses on soi.InventoryOrCourseId equals c.Id
    where u.Id == 5
    select new{ u, p, soi, either i or c};

您必须使用一些外连接技巧来完成此操作,一种简单的方法是通过DefaultIfEmpty()。本质上,您创建一个内部联接,然后用缺失的行扩展它:

var r = from u in Users
    join p in Payments on u.Id equals p.UserId
    join soi in SaleOrderItems on p.ReferenceId equals soi.Id
    join i in Inventories on new {a = soi.InventoryTypeId, b = soi.InventoryOrCourseId } equals new {a = 1, b = i.Id} into g1
    from oi in g1.DefaultIfEmpty()
    join c in Courses on new {a = soi.InventoryTypeId, b = soi.InventoryOrCourseId } equals new {a = 2, b = c.Id} into g2
    from oc in g2.DefaultIfEmpty()
    where u.Id == 5
    select new{ u, p, soi, ic = oi ?? oc};

请注意最后这句话ic = oi ?? oc,由于类型不同,匿名类型将使用 System.Object 声明,因此它可以容纳这两种类型,如果您想使用强类型支持,也许更好的选择是返回 oc 和 ic,然后进行测试。您最好根据稍后使用此查询的方式来决定。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

linq 与 case 条件连接 的相关文章

随机推荐