LINQ:当使用的SingleOrDefault与FirstOrDefault()与过滤标准 [英] LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria
问题描述
考虑IEnumerable的扩展方法的SingleOrDefault()
和 FirstOrDefault()
Consider the IEnumerable extension methods SingleOrDefault()
and FirstOrDefault()
返回序列的唯一元件,或者如果序列是空的一默认值;这种方法抛出一个异常,如果有序列中的多个元素。
Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.
而 FirstOrDefault
从MSDN (当使用presumably的排序依据()
或 OrderByDescending()
或根本没有),
whereas FirstOrDefault
from MSDN (presumably when using an OrderBy()
or OrderByDescending()
or none at all),
返回序列的第一个元素
考虑少数例子查询,它并不总是很清楚什么时候使用这两种方法:
Consider a handful of example queries, it's not always clear when to use these two methods:
var someCust = db.Customers
.SingleOrDefault(c=>c.ID == 5); //unlikely(?) to be more than one, but technically COULD BE
var bobbyCust = db.Customers
.FirstOrDefault(c=>c.FirstName == "Bobby"); //clearly could be one or many, so use First?
var latestCust = db.Customers
.OrderByDescending(x=> x.CreatedOn)
.FirstOrDefault();//Single or First, or does it matter?
问题
什么约定你遵循或暗示决定要使用时,的SingleOrDefault()
和 FirstOrDefault()
在你的LINQ查询?
What conventions do you follow or suggest when deciding to use SingleOrDefault()
and FirstOrDefault()
in your LINQ queries?
推荐答案
当你使用的SingleOrDefault
,明确声明该查询应导致至多的单的结果。在另一方面,当 FirstOrDefault
时,查询可返回结果的任何金额,但你的状态,你只需要第一个。
Whenever you use SingleOrDefault
, you clearly state that the query should result in at most a single result. On the other hand, when FirstOrDefault
is used, the query can return any amount of results but you state that you only want the first one.
我个人觉得语义完全不同的,并使用一个合适的,这取决于预期的效果,提高了可读性。
I personally find the semantics very different and using the appropriate one, depending on the expected results, improves readability.
这篇关于LINQ:当使用的SingleOrDefault与FirstOrDefault()与过滤标准的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!