Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force linq sum to return null

Tags:

c#

linq

I suppose 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;

Sum is always returning 0, why is nullable needed at all? Is there a way to force linq sum to return null? What am I missing here?

like image 803
broadband Avatar asked Apr 21 '17 07:04

broadband


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

like image 126
fubo Avatar answered Oct 24 '22 01:10

fubo


You can try this:

int? sum = intList.TrueForAll(x => x == null) ? null : intList.Sum();
like image 4
daniell89 Avatar answered Oct 24 '22 02:10

daniell89


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;
}
like image 4
Martin Backasch Avatar answered Oct 24 '22 02:10

Martin Backasch