FirstOrDefault: Default value other than null

后端 未结 11 1183
-上瘾入骨i
-上瘾入骨i 2020-12-12 21:37

As I understand it, in Linq the method FirstOrDefault() can return a Default value of something other than null. What I haven\'t worked out is wha

11条回答
  •  旧巷少年郎
    2020-12-12 21:58

    As I understand it, in Linq the method FirstOrDefault() can return a Default value of something other than null.

    No. Or rather, it always returns the default value for the element type... which is either a null reference, the null value of a nullable value type, or the natural "all zeroes" value for a non-nullable value type.

    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?

    For reference types, you can just use:

    var result = query.FirstOrDefault() ?? otherDefaultValue;
    

    Of course this will also give you the "other default value" if the first value is present, but is a null reference...

提交回复
热议问题