我到处搜索,并没有真正找到一个明确的答案,什么时候你想使用. first,什么时候你想使用. firstordefault与LINQ。

什么时候你想用。first ?只有当你想捕捉异常,如果没有结果返回哪里? var result =列表。Where(x => x == "foo").First(); 什么时候使用。firstordefault ?当你总是想默认类型,如果没有结果? var result =列表。Where(x => x == "foo").FirstOrDefault(); 说到这,那塔克呢? var result =列表。Where(x => x == "foo").Take(1);


当前回答

.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.

Skip()和Take()通常在设置结果分页时使用。(比如显示前10个结果,接下来的10个在下一页,等等)

其他回答

someList.First(); // exception if collection is empty.
someList.FirstOrDefault(); // first item or default(Type)

用哪一个? 它应该由业务逻辑决定,而不是担心异常/程序失败。

例如, 如果业务逻辑说我们在任何工作日都不可能有零事务(只是假设)。那么您不应该尝试使用一些聪明的编程来处理这种情况。 我将始终在这样的集合上使用First(),如果有其他东西搞砸了业务逻辑,则让程序失败。

代码:

var transactionsOnWorkingDay = GetTransactionOnLatestWorkingDay();
var justNeedOneToProcess = transactionsOnWorkingDay.First(): //Not FirstOrDefault()

我想看看其他人对此的评论。

如果没有要返回的行,. first()将抛出异常,而. firstordefault()将返回默认值(所有引用类型为NULL)。

因此,如果你准备好并愿意处理一个可能的异常,. first()是很好的。如果您更喜欢检查!= null的返回值,那么. firstordefault()是更好的选择。

但我想这也有点个人偏好。使用哪个对你更有意义,更适合你的编码风格。

当我知道或期望序列至少有一个元素时,我会使用First()。换句话说,当出现异常时,序列为空。

当您知道需要检查是否存在元素时,请使用FirstOrDefault()。换句话说,当序列为空是合法的时候。您不应该依赖异常处理进行检查。(这是不好的做法,可能会影响性能)。

最后,First()和Take(1)之间的区别是First()返回元素本身,而Take(1)返回只包含一个元素的元素序列。

.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.

Skip()和Take()通常在设置结果分页时使用。(比如显示前10个结果,接下来的10个在下一页,等等)

我发现了一个网站,它似乎解释了对FirstOrDefault的需求 http://thepursuitofalife.com/the-linq-firstordefault-method-and-null-resultsets/ 如果查询没有结果,并且您想调用First()或Single()来获得单行…您将得到一个“序列不包含元素”异常。

免责声明:我从未使用过LINQ,所以如果这是错误的,我很抱歉。