英文:
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<>
since the newer language features usually are not supported by expression trees) and constants:
const int desiredIntValue = 1;
list.Where(x=> x.a.b is null or desiredIntValue)
For non-constant values you can do something like:
list.Where(x => (x.a.b ?? desiredIntValue) == desiredIntValue);
Or for nullable value types
list.Where(x => x.a.b.GetValueOrDefault(desiredValue) == desiredValue);
But not sure if it can be considered as shorthand.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论