Keep null when adding Nullable int?

走远了吗. 提交于 2021-02-05 10:44:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!