在SQL中我通常会输出这个,难以阅读 - 是的,但确实有效
(IIF(Table1.Field1 = 1,
-- Field1 is True
IIF(Table2.Field2= 1, (SUM(Table1.Field3+Table1.Field4)),(SUM(Table1.Field3+Table1.Field4)*-1))
, -- Field1 is False
IIF(Table2.Field2= 1, (SUM((Table1.Field3+Table1.Field4)*-1)), (SUM(Table1.Field3+Table1.Field4))))) AS Result
我如何将其转换为Linq查询,我知道我可以做三元组,但是有可能嵌套三元组吗?
此外,我的目标是在一次数据库调用中执行此操作。
答案 0 :(得分:3)
你可以使用ternary operator(?:
)来写这个:
from t in db.Table1
group t by new { t.Field1, t.Field2 } into g
select
g.Key.Field1 == 1
? g.Key.Field2 == 1
? g.Sum(t => t.Field3 + t.Field4)
: -g.Sum(t => t.Field3 + t.Field4)
: g.Key.Field2 == 1
? -g.Sum(t => t.Field3 + t.Field4)
: g.Sum(t => t.Field3 + t.Field4)
但我们可以将其简化为:
from t in db.Table1
group t by new { t.Field1, t.Field2 } into g
let s1 = g.Key.Field1 == 1 ? 1 : -1
let s2 = g.Key.Field2 == 1 ? 1 : -1
select s1 * s2 * g.Sum(t => t.Field3 + t.Field4)