简体   繁体   English

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

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

I am trying to Parse a String into Nullable int, with Linq select.我正在尝试使用 Linq select 将字符串解析为 Nullable int。 The following last line is not working in Select.下面的最后一行在 Select 中不起作用。 Receiving Error below.接收错误如下。 How can it be fixed?如何修复?

Resource: https://stackoverflow.com/a/45066/13889515资源: 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, 

Error: The name 'tempVal' does not exist in the current context错误:名称“tempVal”在当前上下文中不存在

Trying to avoid Extension Methods if possible如果可能,尽量避免扩展方法

Using Net Core 3.1 with C#8在 C#8 中使用 Net Core 3.1

The syntax requires you to define the variable, if you haven't previously.语法要求您定义变量(如果您之前没有定义)。 So use所以用

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

But, your code can be shortened, as tempVal will contain the value you want, you don't need to parse again -但是,您的代码可以缩短,因为tempVal将包含您想要的值,您不需要再次解析 -

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

You can create a new method which should wrap this operation.您可以创建一个新方法来包装此操作。

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