Is there a more elegant way to add nullable ints?

var nums = new int?[] {1, null, 3};
var total = nums.Sum();

This relies on the IEnumerable<Nullable<Int32>>overload of the Enumerable.Sum Method, which behaves as you would expect.

If you have a default-value that is not equal to zero, you can do:

var total = nums.Sum(i => i.GetValueOrDefault(myDefaultValue));

or the shorthand:

var total = nums.Sum(i => i ?? myDefaultValue);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)