繁体   English   中英

C# 8:Linq Select,将字符串解析为 Nullable Int

[英]C# 8: Linq Select, Parse String into Nullable Int

我正在尝试使用 Linq select 将字符串解析为 Nullable int。 下面的最后一行在 Select 中不起作用。 接收错误如下。 如何修复?

资源: https : //stackoverflow.com/a/45066/13889515

var aviationInfo = _dbContext.Cpamlt
                    .Where(c=> c.Account == bppInfoRequestDto.AccountNumber)
                    .Select(cpamlt => new BppAviationInfoDto()
                    {
                        AccountNumberIdentityId = cpamlt.Cpamltid,
                        SerialNumber = cpamlt.Vinserno,
                        Manufacturer = cpamlt.Manmod,
                        MakeModel = cpamlt.Manmak,
                        YearManufactured = Int32.TryParse(cpamlt.Manyr, out tempVal) ? Int32.Parse(cpamlt.Manyr) : (int?)null, 

错误:名称“tempVal”在当前上下文中不存在

如果可能,尽量避免扩展方法

在 C#8 中使用 Net Core 3.1

语法要求您定义变量(如果您之前没有定义)。 所以用

Int32.TryParse(cpamlt.Manyr, out int tempVal)

但是,您的代码可以缩短,因为tempVal将包含您想要的值,您不需要再次解析 -

YearManufactured = Int32.TryParse(cpamlt.Manyr, out int tempVal) ? tempVal : (int?)null,

您可以创建一个新方法来包装此操作。

static int? NullableParse(string input)
{
    int output = 0;

    if (!int.TryParse(input, out output))
    {
        return null;
    }

    return output;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM