-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

2
  • Can't you just create a method CanBeParsed that wraps TryParse Commented Sep 27, 2020 at 2: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. Commented Sep 27, 2020 at 3:14

2 Answers 2

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,
Sign up to request clarification or add additional context in comments.

2 Comments

hi getting new error, Error CS8198 An expression tree may not contain an out argument variable declaration.
gave points and accepted answer, feel free to thumbs up question, thanks !
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;
}

2 Comments

forgot to mention, trying to avoid extension methods if possible
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.