有没有更优雅的方法来添加可为null的int? [英] Is there a more elegant way to add nullable ints?

查看:102
本文介绍了有没有更优雅的方法来添加可为null的int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要添加大量可为null的int类型的变量.我使用空合并运算符将其降低到每行一个变量,但是我觉得有一种更简洁的方法可以做到这一点,例如我不能以某种方式将这些语句链接在一起,我之前在其他代码中已经看到过.

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

推荐答案

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

这依赖于 IEnumerable<Nullable<Int32>>重载 href ="http://msdn.microsoft.com/zh-cn/library/bb345537.aspx" rel ="noreferrer"> Enumerable.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));

或速记:

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

这篇关于有没有更优雅的方法来添加可为null的int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆