linq结合案例条件 [英] linq join with case condition
问题描述
我可以知道在使用linq时如何选择条件"条件吗? 注释掉的代码是我的问题.我该如何放置条件? 我的代码:
Hi may i know how to do a select "case" condition in using linq? The commented out code are my question. how do i put the condition there? my code:
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()
.本质上,您创建一个内部联接,然后使用缺少的行将其展开:
You have to use some outer join trick to accomplish this, one straightforward method is via DefaultIfEmpty()
. Essentially you create an inner join then expand it with missing rows:
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,然后进行测试.您最好根据您后期使用查询的方式来决定.
Be careful about this last statement ic = oi ?? oc
, since the types differ the anonymous type will use System.Object declaration so it can accommodate both types, if you want to use strong typed support maybe a better option would be to return both oc and ic and then test. You should best decide that based on how you use this query late ron.
这篇关于linq结合案例条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!