尝试在c#中使用多个选项执行inline if语句

sla*_*dau 3 .net c# if-statement

所以我有两个可以为空的小数:

s.SwapProfitAmount
s.SwapProfitBps
Run Code Online (Sandbox Code Playgroud)

然后我有一个属性需要设置为其中一个小数的值之一调用Profit.

我想要的是一个行if语句,它将设置ProfitValue可以为空的十进制数中的任何一个HasValue并且具有Value大于0.如果它们都是0,它只会将其设置为0.有意义吗?

编辑:

Profit
Run Code Online (Sandbox Code Playgroud)

是一个string.

cwh*_*ris 6

这应该工作.为什么你需要一行?

Profit = (s.SwapProfitAmount.HasValue && s.SwapProfitAmount.Value > 0 ? s.SwapProfitAmount.Value : s.SwapProfitBps.GetValueOrDefault(0)).ToString();
Run Code Online (Sandbox Code Playgroud)

为了便于阅读......

Profit = (
  s.SwapProfitAmount.HasValue && s.SwapProfitAmount.Value > 0
    ? s.SwapProfitAmount.Value
    : s.SwapProfitBps.GetValueOrDefault(0)
  ).ToString();
Run Code Online (Sandbox Code Playgroud)

既然你说你使用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();
Run Code Online (Sandbox Code Playgroud)

当SwapProfitAmount <= 0或时,这些都将回退到SwapProfitBps== null

最后,就像安德烈所说,你可以使用一个函数......

Profit = GetProfitString(s);
Run Code Online (Sandbox Code Playgroud)

  • @slandau这不是应该在生产中使用的代码.想想以后需要解密它的同事.什么阻止你在函数中用*normal*style编写这个逻辑并稍后从Linq调用它? (2认同)