问题描述
LINQ:
当我确定查询将返回单条记录时,使用 Single()
运算符而不是 First()
是否更有效?/strong>?
Is it more efficient to use the Single()
operator over First()
when ever I know for certain that the query will return a single record?
有区别吗?
推荐答案
如果您期待单条记录,那么在您的代码中明确表示总是好的.
我知道其他人已经写过你为什么使用其中一个,但我想我会说明为什么你不应该使用一个,当你指的是另一个.
注意:在我的代码中,我通常会使用 FirstOrDefault()
和 SingleOrDefault()
,但这是一个不同的问题.
Note: In my code, I will typically use FirstOrDefault()
and SingleOrDefault()
but that's a different question.
以使用复合键( ID
, Lang
)以不同语言存储 Customers
的表为例:
Take, for example, a table that stores Customers
in different languages using a Composite Key ( ID
, Lang
):
DBContext db = new DBContext();
Customer customer = db.Customers.Where( c=> c.ID == 5 ).First();
上面的这段代码引入了一个可能的逻辑错误(难以追踪).它将返回多个记录(假设您有多种语言的客户记录)但它总是只返回第一个......有时可能有效......但其他人无效.这是不可预测的.
This code above introduces a possible logic error ( difficult to trace ). It will return more than one record ( assuming you have the customer record in multiple languages ) but it will always return only the first one... which may work sometimes... but not others. It's unpredictable.
由于您的意图是返回单个 Customer
,请使用 Single()
;
Since your intent is to return a Single Customer
use Single()
;
以下将引发异常(在本例中正是您想要的):
The following would throw an exception ( which is what you want in this case ):
DBContext db = new DBContext();
Customer customer = db.Customers.Where( c=> c.ID == 5 ).Single();
然后,您只需敲击自己的额头,然后对自己说……哎呀!我忘了语言领域!以下是正确的版本:
Then, you simply hit yourself on the forehead and say to yourself... OOPS! I forgot the language field! Following is the correct version:
DBContext db = new DBContext();
Customer customer = db.Customers.Where( c=> c.ID == 5 && c.Lang == "en" ).Single();
First()
在以下场景中很有用:
First()
is useful in the following scenario:
DBContext db = new DBContext();
NewsItem newsitem = db.NewsItems.OrderByDescending( n => n.AddedDate ).First();
它将返回一个对象,并且由于您正在使用排序,它将是返回的最新记录.
It will return ONE object, and since you're using sorting, it will be the most recent record that is returned.
当您认为应该明确返回 1 条记录时使用 Single()
将帮助您避免逻辑错误.
Using Single()
when you feel it should explicitly always return 1 record will help you avoid logic errors.
这篇关于LINQ Single vs First的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!