是否有更优雅的方式来添加可空的整数?

时间:2010-08-30 10:06:03

标签: c# nullable null-coalescing-operator

我需要添加nullable int类型的许多变量。我使用null合并运算符将每行变为一个变量,但我觉得有一种更简洁的方法可以做到这一点,例如:我不能以某种方式将这些陈述链接在一起,我之前在其他代码中看到过。

using System;

namespace TestNullInts
{
    class Program
    {
        static void Main(string[] args)
        {
            int? sum1 = 1;
            int? sum2 = null;
            int? sum3 = 3;

            //int total = sum1 + sum2 + sum3;
            //int total = sum1.Value + sum2.Value + sum3.Value;

            int total = 0;
            total = total + sum1 ?? total;
            total = total + sum2 ?? total;
            total = total + sum3 ?? total;

            Console.WriteLine(total);
            Console.ReadLine();
        }
    }
}

9 个答案:

答案 0 :(得分:50)

var nums = new int?[] {1, null, 3};
var total = nums.Sum();

这取决于IEnumerable<Nullable<Int32>>overload 方法的Enumerable.Sum,其行为与您期望的一样。

如果您的默认值不等于零,则可以执行以下操作:

var total = nums.Sum(i => i.GetValueOrDefault(myDefaultValue));

或简写:

var total = nums.Sum(i => i ?? myDefaultValue);

答案 1 :(得分:22)

total += sum1.GetValueOrDefault();

答案 2 :(得分:12)

最直接地回答这个问题:

int total = (sum1 ?? 0) + (sum2 ?? 0) + (sum3 ?? 0);

这种陈述是&#34;链接&#34;使用+

一起询问

答案 3 :(得分:2)

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);
通过这种方式,您可以拥有任意数量的值。

答案 4 :(得分:1)

如何处理辅助方法 -

static int Sum(params int?[] values)
{
  int total = 0;
  for(var i=0; i<values.length; i++) {
     total += values[i] ?? 0;
  }
  return total;
}

IMO,不是很优雅,但至少可以一次性添加任意数量的数字。

total = Helper.Sum(sum1, sum2, sum3, ...);

答案 5 :(得分:1)

你可以做到

total += sum1 ?? 0;
total += sum2 ?? 0;
total += sum3 ?? 0;

答案 6 :(得分:1)

如何在相应的非可空表达式中用(sumX ?? 0)代替sumX呢?

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

答案 7 :(得分:0)

最简单,最优雅的LINQ用法:

var list = new List<Nullable<int>> { 1, 2, null, 3 };
var sum = list.Sum(s => s ?? 0);
Console.WriteLine(sum);

您需要合并AFAIK以确保结果不可为空。

答案 8 :(得分:0)

如果数组中的所有数字均为空,我希望总数为空。

slotStatusTypesList

测试用例

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

示例实现

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
相关问题