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

1.2k views Asked by At

I am trying to Parse a String into Nullable int, with Linq select. The following last line is not working in Select. Receiving Error below. How can it be fixed?

Resource: 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

Trying to avoid Extension Methods if possible

Using Net Core 3.1 with C#8

2

There are 2 answers

2
Jonesopolis On BEST ANSWER

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 -

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

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