Is there a more elegant way to add nullable ints?

2019-01-25 01:50发布

问题:

I need to add numerous variables of type nullable int. I used the null coalescing operator to get it down to one variable per line, but I have a feeling there is a more concise way to do this, e.g. can't I chain these statements together somehow, I've seen that before in other code.

using System;

namespace TestNullInts
{
    class Program
    {
        static void Main(string[] args)
        {
            int? sum1 = 1;
            int? sum2 = null;
            int? sum3 = 3;

            //int total = sum1 + sum2 + sum3;
            //int total = sum1.Value + sum2.Value + sum3.Value;

            int total = 0;
            total = total + sum1 ?? total;
            total = total + sum2 ?? total;
            total = total + sum3 ?? total;

            Console.WriteLine(total);
            Console.ReadLine();
        }
    }
}

回答1:

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);



回答2:

total += sum1.GetValueOrDefault();

etc.



回答3:

Just to answer the question most directly:

int total = (sum1 ?? 0) + (sum2 ?? 0) + (sum3 ?? 0);

This way the statements are "chained" together as asked using a +



回答4:

List<Nullable<int>> numbers = new List<Nullable<int>>();
numbers.Add(sum1);
numbers.Add(sum2);
numbers.Add(sum3);

int total = 0;
numbers.ForEach(n => total += n ?? 0);

this way you can have as many values as you want.



回答5:

How to about helper method -

static int Sum(params int?[] values)
{
  int total = 0;
  for(var i=0; i<values.length; i++) {
     total += values[i] ?? 0;
  }
  return total;
}

IMO, not very elegant but at least add as many numbers as you want in a one go.

total = Helper.Sum(sum1, sum2, sum3, ...);


回答6:

You could do

total += sum1 ?? 0;
total += sum2 ?? 0;
total += sum3 ?? 0;


回答7:

How about just substituting (sumX ?? 0) for sumX in the corresponding non-nullable expression?

using System; 

namespace TestNullInts 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            int? sum1 = 1; 
            int? sum2 = null; 
            int? sum3 = 3; 

            int total = 0; 
            total += (sum1 ?? 0) + (sum2 ?? 0) + (sum3 ?? 0); 

            Console.WriteLine(total); 
            Console.ReadLine(); 
        } 
    } 
} 


回答8:

Simplest, most elegant usage of LINQ:

var list = new List<Nullable<int>> { 1, 2, null, 3 };
var sum = list.Sum(s => s ?? 0);
Console.WriteLine(sum);

You need the coalesce AFAIK to make sure the result is not nullable.