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


It just matches your input type. If you change your list to List it will return int not int? Since your list is int? this is what it returns ...



+1


source


You can try this:

int? sum = intList.TrueForAll(x => x == null) ? null : intList.Sum();

      

+1


source


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


You can also try this if your linq sum returns null:

int? sum = intList.AsQueryable().Any(a => a.HasValue) ? intList.AsQueryable().Sum(a => a.Value) : (int?)null;

      

0


source







All Articles