Linq sum force to return null
I suppose the answer is trivial:
List<int?> intList = new List<int?>(){null, null, null};
int? sum = list.Sum();
int sum2 = list.Sum(a => a.HasValue ? a.Value : 0);
int sum3 = list.Sum().Value;
The sum always returns 0, why is zero necessary at all? Is there a way to make linq sum return null? What am I missing here?
+3
source to share
5 answers
Here is the implementation of Sum ()
public static int? Sum(this IEnumerable<int?> source) {
if (source == null) throw Error.ArgumentNull("source");
int sum = 0;
checked {
foreach (int? v in source) {
if (v != null) sum += v.GetValueOrDefault();
}
}
return sum;
The reason for not returning null is the way it is implemented - the int sum = 0;
resulting usage can never return null.
+2
source to share
As fubo already wrote:
The reason for rejecting a null value is the way it is implemented - using it
int sum = 0;
as a result can never return null.
Why not write your own extension method
public static int? NullableSum( this IEnumerable<int?> source)
{
int? sum = null;
foreach (int? v in source)
{
if (v != null)
{
if (sum == null)
{
sum = 0;
}
sum += v.GetValueOrDefault()
}
}
return sum;
}
0
source to share