gpt4 book ai didi

LINQ:在 LINQ let 中使用三元 ( ?: ) 是不够的,需要 "IF"但似乎无法让它工作

转载 作者:行者123 更新时间:2023-12-02 06:39:26 24 4
gpt4 key购买 nike

我试图在 LINQ 中的 LET 中包含一个 IF,但我无法让它工作,它似乎适用于三元运算符,但这是 TRUE 或 FALSE,我需要有两个以上的选项。

我认为这很好地解释了它

基本上我有一个选择,它使用数据库中的连接来选择项目。然后我得到每条记录的状态,但我必须根据 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
}

任何人都知道如何执行标准 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;
}

如果您没有将状态用于 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;
}

(1) 三元运算符是任何接受三个参数的运算符,目前C#中只有一个称为条件运算符

关于LINQ:在 LINQ let 中使用三元 ( ?: ) 是不够的,需要 "IF"但似乎无法让它工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11029980/

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