Is there a more elegant way to add nullable ints?

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

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

提交回复
热议问题