如果FirstOrDefault返回null,请从FirstOrDefault中选择一个属性 [英] selecting a property from FirstOrDefault in case FirstOrDefault returns null
问题描述
我要发表以下声明:
var block = blocksById.FirstOrDefault(X => X.Value == tracResult.ID).Key
我的问题是,在我拥有FirstOrDefault null值的情况下,如何更正确地处理它.
我只是觉得if
陈述唯一的解决方案……
My question is how to deal with it more correctly in case I have FirstOrDefault null value.
I just not feel that if
statments the only solution that can be here...
推荐答案
Since the introduction of the null conditional operators (?), it's as simple as:
var block = blocksById.FirstOrDefault(X => X.Value == tracResult.ID)?.Key;
请记住,在这种情况下,即使Value
是int
,block
的类型也将是Nullable<int>
,因此也可能是null
.
Keep in mind that in this scenario, even if Value
is an int
, block
will be of type Nullable<int>
, and hence, can be null
.
However if what you want to assign a default value if null
is returned you can make use of null coalescing operator (??) is this way:
var block = blocksById.FirstOrDefault(X => X.Value == tracResult.ID)?.Key ?? 6;
尽管如此,对于更复杂的Select
语句,以下内容仍然有效...
Nevertheless, for more complex Select
statements, the following is still valid...
将其拆分为Where
和Select
:
var block = blocksById.Where(x => x.Value == tracResult.ID)
.Select(x => x.Key)
.FirstOrDefault();
这样,如果FirstOrDefault返回null
,您将不会收到NullRefferenceException.
That way you won't get a NullRefferenceException if the FirstOrDefault returns null
.
或者,您可以给它一个默认值,如下所示:
Alternative you can give it a default value like this:
var block = blocksById.Where(x => x.Value == tracResult.ID)
.Select(x => x.Key)
.FirstOrDefault() ?? somedefaultvalue;
或如@Silvermind所述,用于非可空到可空类型(int
):
Or as @Silvermind stated for non nullable to nullable types (int
's):
var block = blocksById.Where(x => x.Value == tracResult.ID)
.Select(x => (int?) x.Key)
.FirstOrDefault() ?? somedefaultvalue;
更新:有些人似乎怀疑这是否是一个有效的用例,并争辩说必须在程序的稍后部分对null进行检查.
Update: some people seems to have doubts about this being a valid use case and argue that the check for null has to be done later on in the program.
尽管在很多情况下是这样,但不一定总是必须为true,或者如果是,则这种方式可能更方便.
While in a lot of circumstances this is the case, is doesn't always have to be true, or if it is, it might be more convenient this way.
一些例子:
//one liner, null check delegated (not my favorite):
return SomeCalculatedValue(collection.Where(condition).Select(selection).FirstOrDefault());
//or a mapping (shown with default value):
var result = collection.Where(condition)
.Select(c =>
{
Foo = c.Foo,
Bar = c.Bar
}).FirstOrDefault()) ?? new { Foo = "New", Bar = "Empty"};
这篇关于如果FirstOrDefault返回null,请从FirstOrDefault中选择一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!