Home > other >  lambda check for null and then set to 0
lambda check for null and then set to 0

Time:05-27

In this example I have a nullable int and in the lambda I want to set it to 0 and then do a compare. If it null I want to set it to 0 and then campare it to <= 1. How can HasValue in the lambda where condition ?

var exchangeAttemptsList = ExchangeRequestList
                          .Where( x => x.ExchangeAttempts.HasValue
                            ? x.ExchangeAttempts.Value
                            : 1 <= 1
                          )
                          .ToList()
                          ;

Sample

https://dotnetfiddle.net/f5BD4n

CodePudding user response:

This expression makes no sense (and doesn't compile):

x => x.ExchangeAttempts.HasValue
   ? x.ExchangeAttempts.Value
   : 1 <= 1

That is the exact equivalent (assuming that ExchangeAttempts is an int? of:

int lambda( x MyClass )
{
  int result;

  if ( x.ExchangeAttempts.HasValue )
  {
    result = x.ExchangeAttempts.Value ;
  }
  else
  {
    result = 1 <= 1 ; 
  }
  return result;
}

It fails to compile because the expression 1 <= 1 evaluates to true.

If what you want to do is assign a default value of 1 if ExchangeAttempts is null, just say:

x => (x.ExchangeAttempts ?? 1) <= 1

It's shorter and more concise, and better expresses your intent.

Or, better yet:

x => x.ExchangeAttempts == null || x.ExchangeAttempts <= 1

Logical expressions short circuit, so the alternative is only ever tried if the first text fails, so the above returns true when either

  • x.ExchangeAttempts has no value, or
  • x.ExchangeAttempts has a value less than or equal to 1

And returns false when

  • x.ExchangeAttempts has a value and that value is > 1.
  • Related