Is there a more elegant way to add nullable ints?

后端 未结 9 952
陌清茗
陌清茗 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:07

    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.

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

    If all numbers in the array are null I would expect the total to be null.

    // E.g. 
    int? added = null, updated = null, deleted = null; 
    ...
    int? total = added + updated + deleted; // null i.e. nothing has been done.
    

    Test Cases

    Sum(new int?[] { null, null}).Dump(); // null   
    Sum(new int?[] { 1, null}).Dump();    // 1
    Sum(new int?[] { null, 2}).Dump();    // 2
    Sum(new int?[] { 1, 2}).Dump();       // 3
    

    Sample Implementation

    int? Sum(int?[] numbers)
    {
        int? total = null;
    
        for (int i = 0; i < numbers.Length; i++)
        {
            int? item = numbers[i];
            if (item != null)
            {
                if (total == null)
                {
                    total = item;
                }
                else
                {
                    total += item;
                }
            }
        }
        
        return total;
    }
    
    0 讨论(0)
  • 2020-12-17 08:13

    You could do

    total += sum1 ?? 0;
    total += sum2 ?? 0;
    total += sum3 ?? 0;
    
    0 讨论(0)
  • 2020-12-17 08:14
    total += sum1.GetValueOrDefault();
    

    etc.

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

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

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