Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 what kind of things other than null can be returned by this (and similar) method when there are no items in the query result. 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
625 views
Welcome To Ask or Share your Answers For Others

1 Answer

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...