问题描述
考虑 IEnumerable 扩展方法 SingleOrDefault()
和 FirstOrDefault()
Consider the IEnumerable extension methods SingleOrDefault()
and FirstOrDefault()
MSDN 文档 SingleOrDefault
:
返回序列的唯一元素,如果序列为空,则返回默认值;如果序列中有多个元素,此方法将引发异常.
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 (大概在使用 OrderBy()
或 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?
问题
在决定在 LINQ 查询中使用 SingleOrDefault()
和 FirstOrDefault()
时,您遵循或建议哪些约定?
What conventions do you follow or suggest when deciding to use SingleOrDefault()
and FirstOrDefault()
in your LINQ queries?
推荐答案
每当你使用 SingleOrDefault
,您清楚地声明该查询最多应该产生一个 single 结果.另一方面,当 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() 与过滤条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!