问题
I want to add nullable int?
and keep null
when all values are null
.
I would like this results :
1 + 2 = 3
1 + null = 1
null + null = null
O + null = 0
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
I have seen this thread : Is there a more elegant way to add nullable ints?
With linq :
var nums = new int?[] {null, null, null};
var total = nums.Sum(); // 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 ?
回答1:
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);
}
Functionality wise it does much the same thing as your custom Sum
method, without iterating through the array twice.
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.
Thus, if all inputs are null
it returns null
- otherwise it acts basically the same way as LINQ's Sum
.
来源:https://stackoverflow.com/questions/49172458/keep-null-when-adding-nullable-int