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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…