0

Here i am using simple list and one of the ageto string column is null

I am check in linq query if value not found then to return null. But value cannot be null error is coming up

var list = new[]
    {
        new { AgeFrom = "0", AgeTo="24"},
        new { AgeFrom = "70", AgeTo= (string)null}
    }.ToList();


var result = from r in list 
                 select new EmployeeDTO 
         {
           //AgeFrom Column is int? in DTO  
           AgeFrom = Convert.ToInt32(r.AgeFrom),
           //AgeTo Column is int? in DTO    
           AgeTo = Convert.ToInt32(r.AgeTo ?? null)
         }
4
  • You're converting null to int Commented Aug 30, 2017 at 18:20
  • but AgeTo column in DTO is nullable int Commented Aug 30, 2017 at 18:21
  • Doesn't matter what it is in the DTO, Convert.ToInt32() does not take a null parameter Commented Aug 30, 2017 at 18:22
  • This code works for me as is, I don't understand the problem. Commented Aug 30, 2017 at 18:24

2 Answers 2

3

Try this:

AgeTo = String.IsNullOrEmpty(r.AgeTo) ? (int?)null : (int?)Convert.ToInt32(r.AgeTo);

Which makes your code:

    var list = new[]
    {
        new { AgeFrom = "0", AgeTo="24"},
        new { AgeFrom = "70", AgeTo= (string)null}
    }.ToList();


    var result = from r in list 
                 select new EmployeeDTO 
      {
        //AgeFrom Column is int? in DTO  
        AgeFrom = Convert.ToInt32(r.AgeFrom),
        //AgeTo Column is int? in DTO    
        String.IsNullOrEmpty(r.AgeTo) ? (int?)null : (int?)Convert.ToInt32(r.AgeTo)
      };

Convert.ToInt32 can not convert null to an integer, that will always throw an exception.

Sign up to request clarification or add additional context in comments.

4 Comments

Getting this error Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'int'
add explicit cast to the values being set: (int?)null : (int?)Convert.ToInt32(r.AgeTo)
Yea, looked over the nullable property, thanks @BurnsBA
Getting value cannot be null error ...Argument Null Exception
1

One option would be to change:

AgeTo = Convert.ToInt32(r.AgeTo ?? null)

to:

AgeTo = r.AgeTo != null ? Convert.ToInt32(r.AgeTo) : null

The statement r.AgeTo ?? null is an example of the null-coalescing operator, which, in your case, is essentially saying that if r.AgeTo is null, then use null instead. As this isn't what you were trying to achieve, you are in fact passing null into Convert.ToInt32, which is causing your error.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.