尝试在c#中使用多个选项执行内联if语句
所以我有两个可为空的小数:尝试在c#中使用多个选项执行内联if语句,c#,.net,if-statement,C#,.net,If Statement,所以我有两个可为空的小数: s.SwapProfitAmount s.SwapProfitBps 然后我有一个属性,它需要设置为这些小数中的一个叫做Profit的值 我想要的是一个行if语句,它将利润设置为值,该值是HasValue且值大于0的任意一个可空小数的值。如果它们都是0,则只会将其设置为0。有道理吗 编辑: 是一个字符串您可以尝试以下方法 Profit = (s.SwapProfitAmount.HasValue && s.SwapProfitAmount.Valu
s.SwapProfitAmount
s.SwapProfitBps
然后我有一个属性,它需要设置为这些小数中的一个叫做Profit
的值
我想要的是一个行if语句,它将利润
设置为值
,该值是HasValue
且值
大于0的任意一个可空小数的值。如果它们都是0,则只会将其设置为0。有道理吗
编辑:
是一个
字符串
您可以尝试以下方法
Profit = (s.SwapProfitAmount.HasValue && s.SwapProfitAmount.Value > 0) ? s.SwapProfitAmount.Value : (s.SwapProfitBps.HasValue && s.SwapProfitBps.Value > 0) ? s.SwapProfitBps.Value : 0) + "";
试试这个:
Profit = s.SwapProfitAmount.HasValue && s.SwapProfitAmount > 0 ?
s.SwapProfitAmount.Value.ToString() :
s.SwapProfitBps && s.SwapProfitBps > 0 ? s.SwapProfitBps.Value.ToString() : "0";
这应该行得通。为什么您需要在一行中使用这个
Profit = (s.SwapProfitAmount.HasValue && s.SwapProfitAmount.Value > 0 ? s.SwapProfitAmount.Value : s.SwapProfitBps.GetValueOrDefault(0)).ToString();
为了可读性
Profit = (
s.SwapProfitAmount.HasValue && s.SwapProfitAmount.Value > 0
? s.SwapProfitAmount.Value
: s.SwapProfitBps.GetValueOrDefault(0)
).ToString();
既然你说你在用LINQ,这可能适用于
var results = from s in somethings
let bps = s.SwapProfitBps.GetValueOrDefault(0)
let amount = s.SwapProfitAmount
let profit = amount.HasValue && amount.Value > 0
? amount.Value
: bps
select profit.ToString();
当SwapProfitAmountMath.Max(s.SwapProfitAmount±0,s.SwapProfitBps±0)
问题是,您没有提到如果它们都不为null且>0,该怎么办
如果您想要字符串,请执行以下操作:
Math.Max(s.swaprofitamount?0,s.swaprofitbps?0).ToString()
C#中三元运算符的格式为:
但是,由于您只检查空值,因此可以使用coalesce
运算符,其工作原理如下:
(nullableObject1) ?? (nullableObject2)
这相当于
(nullableObject1 != null) ? nullableObject1 : (nullableObject2)
您可以将这些运算符串在一起,不过应该使用括号来帮助使用三元运算符使语句更清晰。这两种方法都有效,内联if语句非常简单。如果要嵌套它,使用它并使其可读的最简单方法是将语句封装在()中
然而,这可能会变得相当混乱。这相当于实际放置if语句
或者,如果它们可以为空。您可以执行以下操作
Profit = ((s.SwapProfitAmount.getValueOrDefault() > s.SwapProfitBps.getValueOrDefault() && s.SwapProfitAmount.HasValue) ? s.SwapProfitAmount.getValueOrDefault() : s.SwapProfitBps.getValueOrDefault();
刚刚添加了一个编辑。Profit是一个字符串,因此无法编译,错误是error 31无法确定条件表达式的类型,因为'string'和'int'之间没有隐式转换实际上,您的答案将导致“swaprofit”的值,即使它为零,但它应该选择另一个。啊,是的,我以为他是说0,因为看起来像是家庭作业。。。为什么需要一条直线?如果它们都大于零呢?如果其中一个或两个都有负值呢?为什么必须是if语句?这里有更好的方法,我只需要一行,因为这都在一个范围内linq@slandau这不是应该在生产中使用的代码。想想以后需要破译的同事。是什么阻止您在函数中以正常样式编写此逻辑并在以后从Linq调用它?Null不是他检查的唯一条件。他想选择非空值和非零值(如果有的话)。
(nullableObject1) ?? (nullableObject2)
(nullableObject1 != null) ? nullableObject1 : (nullableObject2)
Result = ( (evaluate Truth) ? (return if True) : (return if False));
// the result of nesting inline if statements.
MyValue = ( [statement] ? ( [another Statement] ? true : false) : ([another statement] ? false : ([another stamement] ? true : false)));
Profit = ((s.SwapProfitAmount.getValueOrDefault() > s.SwapProfitBps.getValueOrDefault() && s.SwapProfitAmount.HasValue) ? s.SwapProfitAmount.getValueOrDefault() : s.SwapProfitBps.getValueOrDefault();