Force linq sum to return null

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's implemented - the usage of int sum = 0; as result can never return null.


As fubo already wrote:

The reason for not returning null is the way it's implemented - the usage of int sum = 0; as result can never return null.

Why not write your own extension method, like this:

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;
}

You can try this:

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

Tags:

C#

Linq