在三元运算符内使用OR
本文关键字:OR 运算符 三元 | 更新日期: 2023-09-27 18:18:16
我想使以下条件,但它是错误的。怎样做才能使它正确呢?
row["Total Serviceable Offers"].ToString() == "a" || "b" ? "0" : "c";
可以有三元内条件吗?
string theRow = row["Total Serviceable Offers"].ToString();
(theRow == "a" || theRow == "b") ? "0" : "c";
我们能在三元条件下得到
||
吗?
是的,你可以。但是在您的方法中,||
位于
row["Total Serviceable Offers"].ToString() == "a"
(布尔表达式)和"b"
(字符串表达式)之间。这就是为什么你的代码不能编译。
您可以将其更改为Contains
或Any
表达式,或者如果有比代码片段显示的更多的比较,则创建一个helper方法。
这里有几种重写表达式的方法:
new[]{"a", "b"}.Contains(row["Total Serviceable Offers"].ToString()) ? "0" : "c";
new[]{"a", "b"}.Any(s => s == row["Total Serviceable Offers"].ToString()) ? "0" : "c";
IsAorB(row["Total Serviceable Offers"].ToString()) ? "0" : "c";
...
bool IsAorB(string s) {
return s == "a" || s == "b";
}
我刚刚在测试程序中运行了int f = (g > 0 || h > 0) ? j : k;
,它没有出错,所以基本上可以。
小心逻辑,祝你好运。
您正在寻找这种语法
(row["Total Serviceable Offers"].ToString() == "a" || row["Total Serviceable Offers"].ToString() == "b") ? "0" : "c";
但我更喜欢Contains()
new[]{"a","b"}.Contains(row["Total Serviceable Offers"].ToString()) ? "0" : "c";