Is there a more elegant way to add nullable ints?

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

提交回复
热议问题