据我了解,在 Linq 中,方法 FirstOrDefault()
可以返回 null 以外的 Default
值。我还没有弄清楚的是,当查询结果中没有项目时,这个(和类似的)方法可以返回除 null 之外的什么类型的东西。是否有任何特定的方法可以设置它,以便如果特定查询没有值,则返回一些预定义值作为默认值?
最佳答案
As I understand it, in Linq the method FirstOrDefault() can return a Default value of something other than null.
没有。或者更确切地说,它总是返回元素类型的默认值...它可以是 null 引用、可为 null 值类型的 null 值,也可以是非元素的自然“全零”值。 -可为空的值类型。
Is there any particular way that this can be set up so that if there is no value for a particular query some predefined value is returned as the default value?
对于引用类型,您可以使用:
var result = query.FirstOrDefault() ?? otherDefaultValue;
当然,如果第一个值存在,但它是一个空引用,这也会为您提供“其他默认值”...
关于.net - 第一或默认 : Default value other than null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12972295/