Is there a more elegant way to add nullable ints?

后端 未结 9 989
陌清茗
陌清茗 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> numbers = new List>();
    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.

提交回复
热议问题