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 ?
Best Answer
One option might be an extension method using
Aggregate
. Something like: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 nonnull
value it starts treating thenull
values as 0.Thus, if all inputs are
null
it returnsnull
- otherwise it acts basically the same way as LINQ'sSum
.