Is there a more elegant way to add nullable ints?

后端 未结 9 953
陌清茗
陌清茗 2020-12-17 07:30

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 conc

相关标签:
9条回答
  • 2020-12-17 08:24
    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.

    0 讨论(0)
  • 2020-12-17 08:24

    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(); 
            } 
        } 
    } 
    
    0 讨论(0)
  • 2020-12-17 08:29

    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 +

    0 讨论(0)
提交回复
热议问题