-3

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

  • Can't you just create a method `CanBeParsed` that wraps `TryParse` – Hayden Sep 27 '20 at 02:47
  • 1
    This looks like an EF Core query, where EF will try to "translate" expression into sql query. You should load result into memory before doing any "not SQL related" manipulations on the result. – Fabio Sep 27 '20 at 03:14

2 Answers2

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 -

YearManufactured = Int32.TryParse(cpamlt.Manyr, out int tempVal) ? tempVal : (int?)null,
Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
  • hi getting new error, Error CS8198 An expression tree may not contain an out argument variable declaration. –  Sep 27 '20 at 02:55
  • gave points and accepted answer, feel free to thumbs up question, thanks ! –  Sep 27 '20 at 07:21
1

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;
}
Hayden
  • 2,902
  • 2
  • 15
  • 29
  • forgot to mention, trying to avoid extension methods if possible –  Sep 27 '20 at 03:00
  • Technically not an extension method, and you can't declare out variables in Linq. Alternative is to do this in a foreach loop, where this would work – Hayden Sep 27 '20 at 03:03