何时使用。首先,何时使用.FirstOrDefault与LINQ? [英] When to use .First and when to use .FirstOrDefault with LINQ?
问题描述
我已搜索周围,还没有真正找到一个明确的答案,当你想使用。首先
,当你想使用 .FirstOrDefault
使用LINQ。
I've searched around and haven't really found a clear answer as to when you'd want to use .First
and when you'd want to use .FirstOrDefault
with LINQ.
-
当你想使用
。首先
?只有当你想要捕捉的异常,如果没有结果返回哪里?
When would you want to use
.First
? Only when you'd want to catch the exception if no results where returned?
var result = List.Where(x => x == "foo").First();
而当你想使用 .FirstOrDefault
?当你总是希望默认类型,如果没有结果?
And when would you want to use .FirstOrDefault
? When you'd always want the default type if no result?
var result = List.Where(x => x == "foo").FirstOrDefault();
对于这个问题,关于采取什么样的?
And for that matter, what about Take?
var result = List.Where(x => x == "foo").Take(1);
推荐答案
我会使用一()
当我知道或者期待序列至少有一个元素。换言之,当它是一个特殊的发生时,序列为空
I would use First()
when I know or expect the sequence to have at least one element. In other words, when it is an exceptional occurrence when the sequence is empty.
使用 FirstOrDefault()
当你知道你将需要检查是否有一个元素与否。换言之,当它是合法的序列是空的。你不应该依赖于异常处理的检查。 (这是不好的做法,可能会降低性能)。
Use FirstOrDefault()
when you know that you will need to check whether there was an element or not. In other words, when it is legal for the sequence to be empty. You should not rely on exception handling for the check. (It is bad practice and might hurt performance).
最后,在一()
和以()
是的区别第一()
返回元素本身,而以()
返回序列中的元素,它包含一个元素。 (如果您传递1作为参数)。
Finally, the difference between First()
and Take()
is that First()
returns the element itself, while Take()
returns a sequence of elements that contains exactly one element. (If you pass 1 as the parameter).
这篇关于何时使用。首先,何时使用.FirstOrDefault与LINQ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!