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

问题描述

我正在尝试使用Linq select将字符串解析为Nullable int。以下最后一行在“选择”中不起作用。接收错误如下。怎么解决

资源: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”在当前上下文中不存在

尽可能避免使用扩展方法

将Net Core 3.1与C#8一起使用

解决方法

如果以前没有使用过,则语法要求您定义变量。所以用

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