有没有更优雅的方法来添加可为空的整数?

发布于 2024-09-16 05:25:36 字数 675 浏览 4 评论 0 原文

我需要添加许多可空 int 类型的变量。我使用空合并运算符将其缩减为每行一个变量,但我感觉有一种更简洁的方法可以做到这一点,例如我不能以某种方式将这些语句链接在一起吗?代码。

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

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 concise way to do this, e.g. can't I chain these statements together somehow, I've seen that before in other code.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

时间海 2024-09-23 05:25:36
var nums = new int?[] {1, null, 3};
var total = nums.Sum();

这依赖于 IEnumerable> Enumerable.Sum a> 方法,其行为如您所期望的那样。

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

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

操作:或简写:

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

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

初与友歌 2024-09-23 05:25:36
total += sum1.GetValueOrDefault();

ETC。

total += sum1.GetValueOrDefault();

etc.

白昼 2024-09-23 05:25:36

只是为了最直接地回答问题:

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

这样,语句就按照使用 + 的要求“链接”在一起

Just to answer the question most directly:

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

This way the statements are "chained" together as asked using a +

念﹏祤嫣 2024-09-23 05:25:36
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);

这样你就可以拥有任意数量的值。

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

this way you can have as many values as you want.

挽清梦 2024-09-23 05:25:36

如何使用辅助方法 -

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, ...);

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, ...);
野生奥特曼 2024-09-23 05:25:36

你可以做

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

You could do

total += sum1 ?? 0;
total += sum2 ?? 0;
total += sum3 ?? 0;
放肆 2024-09-23 05:25:36

在相应的不可空表达式中用 (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(); 
        } 
    } 
} 

How about just substituting (sumX ?? 0) for sumX in the corresponding non-nullable expression?

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(); 
        } 
    } 
} 
清音悠歌 2024-09-23 05:25:36

LINQ 最简单、最优雅的用法:据我

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

所知,您需要合并来确保结果不可为空。

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.

氛圍 2024-09-23 05:25:36

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

// 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

示例实施

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

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文