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

标签 c# .net if-statement

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

s.SwapProfitAmount
s.SwapProfitBps

然后我有一个属性需要设置为这些小数之一的值之一,称为 Profit

我想要的是一行 if 语句,它将 Profit 设置为 HasValue 的可空小数之一的 Value 并且具有一个大于 0 的 Value。如果它们都是 0,它只会将其设置为 0。有意义吗?

编辑:

Profit

是一个字符串

最佳答案

这应该有效。为什么在一行中需要这个?

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();

当 SwapProfitAmount <= 0 时,这些都会回落到 SwapProfitBps或 == null

最后,就像 Andrey 所说的那样,您可以只使用一个函数...

Profit = GetProfitString(s);

关于c# - 尝试在 c# 中使用多个选项执行内联 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5748842/

相关文章:

c# - 两个使用嵌套在一起

c# - 确定类是否是具有多个泛型参数的类型的子类

.net - DTO 和 IQueryable : assembling and disassembling DTOs

.net - System.ExecutionEngineException 失败

javascript - 如何将 xml 传递给 C# 中的 View ?

c# - 是否有一个 Form 事件在将任何内容绘制到屏幕上之前被调用?

c# - 如何将我的方法分配给线程?

if-statement - Tornado 中的 if...else 语句

c# - if else if in while 循环 were else if test 在第一个循环中定义

javascript - 使用 if 语句检查元素是否显示 : block jquery