lambda 检查 null 然后设置为 0

lambda check for null and then set to 0

在此示例中,我有一个可为空的 int,在 lambda 中,我想将其设置为 0,然后进行比较。如果它 null 我想将它设置为 0 然后将其设置为 <= 1。如何在 lambda where 条件中使用 HasValue?

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

样本

https://dotnetfiddle.net/f5BD4n

这个表达式没有意义(并且不编译):

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

这是完全等价的(假设 ExchangeAttemptsint? 的:

int lambda( x MyClass )
{
  int result;

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

编译失败,因为表达式 1 <= 1 的计算结果为 true

如果你想做的是分配默认值 1 如果 ExchangeAttemptsnull,只需说:

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

它更短更简洁,更能表达您的意图。

或者,更好的是:

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

逻辑表达式短路,所以只有在第一次测试失败时才尝试替代方案,所以上面的 returns true

  • x.ExchangeAttempts没有价值,或者
  • x.ExchangeAttempts 的值小于或等于 1

和returnsfalse

  • x.ExchangeAttempts 有一个值并且该值大于 1。