对于与null或必需值进行比较,有没有简写方式?

huangapple go评论69阅读模式
英文:

Any shorthand for comparision to null or required value?

问题

在C#中,有没有一种巧妙的简写方式来实现以下代码:

list.Where(x => x.a.b == null || x.a.b == desiredIntValue)
英文:

Is there any clever shorthand in C# to this:

list.Where(x=> x.a.b == null || x.a.b == desiredIntValue)

答案1

得分: 4

在后续的C#版本中,你可以使用模式匹配和逻辑模式,特别是在这种情况下使用or操作符(假设列表是IEnumerable<>类型,因为较新的语言特性通常不支持表达式树)和常量:

const int desiredIntValue = 1;
list.Where(x => x.a.b is null or desiredIntValue)

对于非常量值,你可以这样做:

list.Where(x => (x.a.b ?? desiredIntValue) == desiredIntValue);

或者对于可空值类型:

list.Where(x => x.a.b.GetValueOrDefault(desiredValue) == desiredValue);

但不确定是否可以将其视为简写形式。

英文:

In later C# versions you can use pattern matching with logical patterns, specifically or in this case (assuming list is IEnumerable&lt;&gt; since the newer language features usually are not supported by expression trees) and constants:

const int desiredIntValue = 1;
list.Where(x=&gt; x.a.b is null or desiredIntValue)

For non-constant values you can do something like:

list.Where(x =&gt; (x.a.b ?? desiredIntValue) == desiredIntValue);

Or for nullable value types

list.Where(x =&gt; x.a.b.GetValueOrDefault(desiredValue) == desiredValue);

But not sure if it can be considered as shorthand.

huangapple
  • 本文由 发表于 2023年8月9日 17:37:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76866428.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定