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


当前回答

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

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

其他回答

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.

首先,Take是一种完全不同的方法。它返回一个IEnumerable< t>而不是一个T,所以这是无效的。

在First和FirstOrDefault之间,当您确定一个元素存在,如果它不存在,那么就会出现错误时,应该使用First。

顺便说一下,如果你的序列包含默认(T)元素(例如null),你需要区分空元素和第一个元素为空,你不能使用FirstOrDefault。

.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个在下一页,等等)

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

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

第()

当您知道结果包含超过1个期望的元素时,您应该只输入序列的第一个元素。

FirstOrDefault ()

FirstOrDefault()与First()类似,不同之处在于,如果没有元素匹配指定的条件,它将返回泛型集合的底层类型的默认值。如果没有找到元素,它不会抛出InvalidOperationException。但如果元素或序列的集合为空,则抛出异常。