问题描述
我四处搜索,并没有真正找到关于何时使用 .First
以及何时使用 .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.
你想在什么时候使用
.First
?只有在没有返回结果的情况下才想捕获异常?
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();
那么,Take 呢?
And for that matter, what about Take?
var result = List.Where(x => x == "foo").Take(1);
推荐答案
当我知道或期望序列至少有一个元素时,我会使用 First()
.换句话说,当序列为空是一种例外情况.
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 that 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).
最后,First()
和Take(1)
的区别在于First()
返回元素本身,而Take(1)
返回恰好包含一个元素的元素序列.
Finally, the difference between First()
and Take(1)
is that First()
returns the element itself, while Take(1)
returns a sequence of elements that contains exactly one element.
这篇关于何时使用 .First 以及何时将 .FirstOrDefault 与 LINQ 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!