添加 Nullable int 时保持 null? [英] Keep null when adding Nullable int?
问题描述
我想添加可为空的 int?
并在所有值为 null
时保留 null
.
I want to add nullable int?
and keep null
when all values are null
.
我想要这样的结果:
1 + 2 = 3
1 + null = 1
null + null = null
O + null = 0
问题是,如果我将一个值与 null 相加,结果为 null
The problem is that if I sum a value with null, the result is null
int? i1 = 1;
int? i2 = null;
int? total = i1 + i2; // null
我看过这个帖子:有没有更优雅的方法来添加可为空整数?
使用 linq :
var nums = new int?[] {null, null, null};
var total = nums.Sum(); // 0
我得到 0 并且我想要空...
I get 0 and I want null...
我发现的唯一方法是创建一个函数:
The only way I have found is to make a function :
static int? Sum(params int?[] values)
{
if (values.All(item => !item.HasValue))
return null;
else
return values.Sum();
}
我有办法在本地做到这一点吗?
I there a way to do that natively ?
推荐答案
一个选项可能是使用 Aggregate
的扩展方法.类似的东西:
One option might be an extension method using Aggregate
. Something like:
public static int? NullableSum(this IEnumerable<int?> values)
{
return values.Aggregate((int?)null, (sum, value)
=> value.HasValue ? (sum ?? 0) + value : sum + 0);
}
在功能方面,它与您的自定义 Sum
方法几乎相同,无需遍历数组两次.
Functionality wise it does much the same thing as your custom Sum
method, without iterating through the array twice.
本质上它将初始值设置为 null
,但是一旦它看到 any 非 null
值,它就会开始处理 null
值为 0.
Essentially it sets the initial value to null
, but as soon as it sees any non null
value it starts treating the null
values as 0.
因此,如果所有输入都是null
,它返回null
- 否则它的行为与LINQ的基本相同总和
.
Thus, if all inputs are null
it returns null
- otherwise it acts basically the same way as LINQ's Sum
.
这篇关于添加 Nullable int 时保持 null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!