When to use .First and when to use .FirstOrDefault with LINQ?(何时使用 .First 以及何时将 .FirstOrDefault 与 LINQ 一起使用?)
问题描述
我四处搜索,并没有真正找到关于何时使用 .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 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:何时使用 .First 以及何时将 .FirstOrDefault 与 LINQ 一起使用?


基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01