Mar*_*tin 2 linq entity-framework
我试图在我的LET中包含一个IF在LINQ但我无法使它工作,它似乎适用于三元运算符,但这是正确或错误,我需要有两个以上的选项.
我认为这很好地解释了它
基本上我有一个选择,它使用来自DB的连接选择项目.然后我得到每条记录的状态,但我必须根据products.type中的类型在不同的表上进行连接
var tst = from p in products join i in info on p.id equals i.pid
// if p.type = "home" then ...
let status = from s in homestatus
select new { status = s.status }
// if p.type ="offshore" then
let status = from s in offshorestatus
select new { status = s.status }
// if p.type ="internal" then
let status = from s in internalestatus
select new { status = s.status }
select new {
name = p.name,
status = status.StatusText
}
Run Code Online (Sandbox Code Playgroud)
任何人都有任何想法如何做标准IF所以我可以选择我希望执行哪个状态(让).
提前致谢
您可以使用条件运算符(1)
var tst = from p in products join i in info on p.id equals i.pid
let status = p.type = "home" ? homestatus.Select(s=>s.status) :
p.type = "offshore" ? offshorestatus.Select(s=>s.status) :
p.type = "internal" ? internalestatus.Select(s=>s.status) : null
select new {
name = p.name,
status = status != null ? status.StatusText : string.Empty;
}
Run Code Online (Sandbox Code Playgroud)
如果您没有使用StatusText以外的任何其他状态,您也可以这样做
var tst = from p in products join i in info on p.id equals i.pid
let status = (p.type = "home" ? homestatus.Select(s=>s.status.StatusText) :
p.type = "offshore" ? offshorestatus.Select(s=>s.status.StatusText) :
p.type = "internal" ? internalestatus.Select(s=>s.status.StatusText) : null) ?? string.Empty
select new {
name = p.name,
status = status;
}
Run Code Online (Sandbox Code Playgroud)
(1)三元运算符是任何带有三个参数的运算符,其中目前只有一个在C#中称为条件运算符