gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:20:39 25 4
gpt4 key购买 nike

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

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/

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