ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

NullableSum

Takes an array of nullable values and sums them up. Can be easily replaced with int?

Source

public static double? NullableSum(this IEnumerable<double?> source)
{
    double? sum = null;
    foreach (var v in source)
    {
        if (v == null) continue;
        if (sum == null)
        {
            sum = 0;
        }

        sum += v.GetValueOrDefault();
    }

    return sum;
}

Example

var myNumbers = new List<double?>
{
    null,1,2
};

Assert.AreEqual(3, myNumbers.NullableSum());

Author: kl00t

Submitted on: 17 jun. 2019

Language: C#

Type: double?

Views: 4368