我到处搜索,并没有真正找到一个明确的答案,什么时候你想使用. 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);


当前回答

Others have very well described the difference between First() and FirstOrDefault(). I want to take a further step in interpreting the semantics of these methods. In my opinion FirstOrDefault is being overused a lot. In the majority of the cases when you’re filtering data you would either expect to get back a collection of elements matching the logical condition or a single unique element by its unique identifier – such as a user, book, post etc... That’s why we can even get as far as saying that FirstOrDefault() is a code smell not because there is something wrong with it but because it’s being used way too often. This blog post explores the topic in details. IMO most of the times SingleOrDefault() is a much better alternative so watch out for this mistake and make sure you use the most appropriate method that clearly represents your contract and expectations.

其他回答

好吧,让我说说我的意见。 First / Firstordefault用于使用第二个构造函数。我不会解释它是什么,但它是指你可能总是使用一个,因为你不想引起异常。

person = tmp.FirstOrDefault(new Func<Person, bool>((p) =>
{
    return string.IsNullOrEmpty(p.Relationship);
}));

Linq有很多方法来实现对集合的简单查询,只要我们在sql中写入连接,过滤器可以根据需要或必要性先应用或最后应用。

下面是一个示例,我们可以在集合中找到带有id的元素。 为了进一步说明这一点,当一个集合至少有一条记录时,方法First和FirstOrDefault理想情况下会返回same。但是,如果集合可以为空的话。那么First将返回一个异常,而FirstOrDefault将返回null或默认值。例如,int将返回0。因此,虽然说使用such是个人偏好,但最好使用FirstOrDefault来避免异常处理。

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

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

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

代码:

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

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

第一:

返回序列的第一个元素 抛出异常:结果中没有元素 使用when:当期望有多个元素,而您只想要第一个元素时

FirstOrDefault:

返回序列的第一个元素,如果没有找到元素,则返回默认值 抛出异常:仅当源为空时 使用when:当期望有多个元素,而您只想要第一个元素时。同样,结果为空也是可以的

来自:http://www.technicaloverload.com/linq-single-vs-singleordefault-vs-first-vs-firstordefault/

这种类型的函数属于元素操作符。下面定义了一些有用的元素操作符。

第一/ FirstOrDefault 去年/ LastOrDefault 单/ SingleOrDefault

当需要根据特定条件从序列中选择单个元素时,我们使用元素操作符。这里有一个例子。

  List<int> items = new List<int>() { 8, 5, 2, 4, 2, 6, 9, 2, 10 };

First()操作符返回序列满足条件后的第一个元素。如果没有找到元素,则抛出异常。

Int result = items。Where(item => item == 2).First();

FirstOrDefault()操作符返回满足条件后序列的第一个元素。如果没有找到元素,则返回该类型的默认值。

Int result1 = items。Where(item => item == 2).FirstOrDefault();