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?
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.
You can try this:
int? sum = intList.TrueForAll(x => x == null) ? null : intList.Sum();
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With