C# 何时使用 .First 以及何时使用 .FirstOrDefault 与 LINQ?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1024559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When to use .First and when to use .FirstOrDefault with LINQ?
提问by Metro Smurf
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
以及何时要.FirstOrDefault
与 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();
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);
你想
.First
什么时候使用?仅当您想在没有返回结果的情况下捕获异常时?var result = List.Where(x => x == "foo").First();
你想
.FirstOrDefault
什么时候使用?如果没有结果,您何时总是想要默认类型?var result = List.Where(x => x == "foo").FirstOrDefault();
就此而言,Take 呢?
var result = List.Where(x => x == "foo").Take(1);
采纳答案by driis
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.
First()
当我知道或期望序列至少有一个元素时,我会使用。换句话说,当序列为空是异常情况时。
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).
使用FirstOrDefault()
时,你知道你需要检查是否有一个元素或没有。换句话说,当序列为空时是合法的。您不应依赖异常处理进行检查。(这是不好的做法,可能会损害性能)。
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()
和Take(1)
是First()
返回元素本身,而Take(1)
包含恰好一个元件返回元素的序列。
回答by marc_s
.First()
will throw an exception if there's no row to be returned, while .FirstOrDefault()
will return the default value (NULL
for all reference types) instead.
.First()
如果没有要返回的行,将抛出异常,而.FirstOrDefault()
将返回默认值(NULL
对于所有引用类型)。
So if you're prepared and willing to handle a possible exception, .First()
is fine. If you prefer to check the return value for != null
anyway, then .FirstOrDefault()
is your better choice.
因此,如果您已准备好并愿意处理可能的异常,那.First()
很好。如果您更喜欢检查返回值!= null
,那么这.FirstOrDefault()
是您更好的选择。
But I guess it's a bit of a personal preference, too. Use whichever makes more sense to you and fits your coding style better.
但我想这也有点个人喜好。使用对您更有意义并且更适合您的编码风格的那个。
回答by Jeroen Landheer
.First
will throw an exception when there are no results. .FirstOrDefault
won't, it will simply return either null (reference types) or the default value of the value type. (e.g like 0
for an int.) The question here is not when you want the default type, but more: Are you willing to handle an exception or handle a default value? Since exceptions should be exceptional, FirstOrDefault
is preferred when you're not sure if you're going to get results out of your query. When logically the data should be there, exception handling can be considered.
.First
没有结果时会抛出异常。.FirstOrDefault
不会,它只会返回 null(引用类型)或值类型的默认值。(例如,0
对于 int。)这里的问题不是您何时需要默认类型,而是更多:您愿意处理异常还是处理默认值?由于异常应该是异常的,FirstOrDefault
因此当您不确定是否要从查询中获得结果时,它是首选。当逻辑上数据应该在那里时,可以考虑异常处理。
Skip()
and Take()
are normally used when setting up paging in results. (Like showing the first 10 results, and the next 10 on the next page, etc.)
Skip()
并且Take()
通常在结果中设置分页时使用。(比如显示前 10 个结果,以及下一页的下 10 个结果,等等)
Hope this helps.
希望这可以帮助。
回答by Mehrdad Afshari
First of all, Take
is a completely different method. It returns an IEnumerable<T>
and not a single T
, so that's out.
首先,Take
是一种完全不同的方法。它返回 anIEnumerable<T>
而不是 single T
,所以就这样了。
Between First
and FirstOrDefault
, you should use First
when you're sure that an element exists and if it doesn't, then there's an error.
在First
and之间FirstOrDefault
,您应该First
在确定某个元素存在时使用,如果不存在,则出现错误。
By the way, if your sequence contains default(T)
elements (e.g. null
) and you need to distinguish between being empty and the first element being null
, you can't use FirstOrDefault
.
顺便说一句,如果您的序列包含default(T)
元素(例如null
)并且您需要区分为空和第一个元素为null
,则不能使用FirstOrDefault
.
回答by NULL
I found a website that apperars to explain the need for FirstOrDefault
http://thepursuitofalife.com/the-linq-firstordefault-method-and-null-resultsets/
If there are no results to a query, and you want to to call First() or Single() to get a single row... You will get an “Sequence contains no elements” exception.
我发现一个网站似乎解释了 FirstOrDefault 的必要性
http://thepursuitofalife.com/the-linq-firstordefault-method-and-null-resultsets/
如果查询没有结果,并且您想调用 First () 或 Single() 获取单行...您将收到“序列不包含元素”异常。
Disclaimer: I have never used LINQ, so my apologies if this is way off the mark.
免责声明:我从未使用过 LINQ,所以如果这有点过分,我深表歉意。
回答by Manish Basantani
someList.First(); // exception if collection is empty.
someList.FirstOrDefault(); // first item or default(Type)
Which one to use? It should be decided by the business logic, and not the fear of exception/programm failure.
使用哪一种?应该由业务逻辑决定,而不是担心异常/程序失败。
For instance, If business logic says that we can not have zero transactions on any working day (Just assume). Then you should not try to handle this scenario with some smart programming. I will always use First() over such collection, and let the program fail if something else screwed up the business logic.
例如,如果业务逻辑说我们在任何工作日都不能有零交易(假设)。那么您不应该尝试通过一些智能编程来处理这种情况。我将始终在此类集合上使用 First(),如果其他事情搞砸了业务逻辑,则让程序失败。
Code:
代码:
var transactionsOnWorkingDay = GetTransactionOnLatestWorkingDay();
var justNeedOneToProcess = transactionsOnWorkingDay.First(): //Not FirstOrDefault()
I would like to see others comments over this.
我希望看到其他人对此发表评论。
回答by Arian
Ok let me give my two cents. First / Firstordefault are for when you use the second constructor. I won't explain what it is, but it's when you would potentially always use one because you don't want to cause an exception.
好吧,让我给我的两分钱。First / Firstordefault 用于当您使用第二个构造函数时。我不会解释它是什么,但是当您可能总是使用一个时,因为您不想导致异常。
person = tmp.FirstOrDefault(new Func<Person, bool>((p) =>
{
return string.IsNullOrEmpty(p.Relationship);
}));
回答by user2051770
First:
第一的:
- Returns the first element of a sequence
- Throws exception: There are no elements in the result
- Use when: When more than 1 element is expected and you want only the first
- 返回序列的第一个元素
- 抛出异常:结果中没有元素
- 何时使用:当需要超过 1 个元素并且您只想要第一个元素时
FirstOrDefault:
首先或默认:
- Returns the first element of a sequence, or a default value if no element is found
- Throws exception: Only if the source is null
- Use when: When more than 1 element is expected and you want only the first. Also it is ok for the result to be empty
- 返回序列的第一个元素,如果没有找到元素,则返回默认值
- 抛出异常:仅当源为空时
- 何时使用:当需要超过 1 个元素并且您只想要第一个元素时。结果为空也可以
From: http://www.technicaloverload.com/linq-single-vs-singleordefault-vs-first-vs-firstordefault/
来自:http: //www.technicaloverload.com/linq-single-vs-singleordefault-vs-first-vs-firstordefault/
回答by Mukesh Kumar
First()
第一的()
- Returns first element of a sequence.
- It throw an error when There is no element in the result or source is null.
- you should use it,If more than one element is expected and you want only first element.
- 返回序列的第一个元素。
- 当结果中没有元素或源为空时,它会抛出错误。
- 您应该使用它,如果需要多个元素并且您只想要第一个元素。
FirstOrDefault()
首先或默认()
- Returns first element of a sequence, or a default value if no element is found.
- It throws an error Only if the source is null.
- you should use it, If more than one element is expected and you want only first element. Also good if result is empty.
- 返回序列的第一个元素,如果未找到元素,则返回默认值。
- 仅当源为空时才会引发错误。
- 您应该使用它,如果需要多个元素并且您只想要第一个元素。如果结果为空也很好。
We have an UserInfos table, which have some records as shown below. On the basis of this table below I have created example...
我们有一个 UserInfos 表,其中有一些记录,如下所示。根据下表,我创建了示例...
How to use First()
如何使用 First()
var result = dc.UserInfos.First(x => x.ID == 1);
There is only one record where ID== 1. Should return this record
ID: 1 First Name: Manish Last Name: Dubey Email: [email protected]
只有一条记录 ID== 1。应返回此记录
ID:1 名字:Manish 姓氏:Dubey 电子邮件:[email protected]
var result = dc.UserInfos.First(x => x.FName == "Rahul");
There are multiple records where FName == "Rahul". First record should be return.
ID: 7 First Name: Rahul Last Name: Sharma Email: [email protected]
有多个记录,其中 FName == "Rahul"。第一个记录应该是返回。
ID:7 名字:Rahul 姓氏:Sharma 电子邮件:[email protected]
var result = dc.UserInfos.First(x => x.ID ==13);
There is no record with ID== 13. An error should be occur.
InvalidOperationException: Sequence contains no elements
没有 ID== 13 的记录。应该会发生错误。
InvalidOperationException:序列不包含任何元素
How to Use FirstOrDefault()
如何使用 FirstOrDefault()
var result = dc.UserInfos.FirstOrDefault(x => x.ID == 1);
There is only one record where ID== 1. Should return this record
ID: 1 First Name: Manish Last Name: Dubey Email: [email protected]
只有一条记录 ID== 1。应返回此记录
ID:1 名字:Manish 姓氏:Dubey 电子邮件:[email protected]
var result = dc.UserInfos.FirstOrDefault(x => x.FName == "Rahul");
There are multiple records where FName == "Rahul". First record should be return.
ID: 7 First Name: Rahul Last Name: Sharma Email: [email protected]
有多个记录,其中 FName == "Rahul"。第一个记录应该是返回。
ID:7 名字:Rahul 姓氏:Sharma 电子邮件:[email protected]
var result = dc.UserInfos.FirstOrDefault(x => x.ID ==13);
There is no record with ID== 13. The return value is null
没有ID==13的记录,返回值为空
Hope it will help you to understand when to use First()
or FirstOrDefault()
.
希望它可以帮助您了解何时使用First()
或FirstOrDefault()
。
回答by Kye
Another difference to note is that if you're debugging an application in a Production environment you might not have access to line numbers, so identifying which particular .First()
statement in a method threw the exception may be difficult.
另一个需要注意的区别是,如果您在生产环境中调试应用程序,您可能无法访问行号,因此识别方法中的哪个特定.First()
语句引发了异常可能很困难。
The exception message will also not include any Lambda expressions you might have used which would make any problem even are harder to debug.
异常消息也不会包含您可能使用过的任何 Lambda 表达式,这会使任何问题甚至更难以调试。
That's why I always use FirstOrDefault()
even though I know a null entry would constitute an exceptional situation.
这就是为什么我总是使用FirstOrDefault()
即使我知道空条目会构成特殊情况。
var customer = context.Customers.FirstOrDefault(i => i.Id == customerId);
if (customer == null)
{
throw new Exception(string.Format("Can't find customer {0}.", customerId));
}