LINQ单VS第一 [英] LINQ Single vs First

查看:191
本文介绍了LINQ单VS第一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

LINQ:

时它更有效地使用了单()运营商在一()当过,我知道肯定该查询将返回一个记录

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?

时有区别吗?

推荐答案

我知道别人都写,为什么你使用一个或另一个,但我想我会说明为什么你不应该使用一个,当你的的意思是其它。

If you're expecting a Single record, it's always good to be explicit in your code.

I know others have written why you use one or the other, but I thought I'd illustrate why you should NOT use one, when you mean the other.

注:在我的code,我通常会使用 FirstOrDefault()的SingleOrDefault()但是这是一个不同的问题。

Note: In my code, I will typically use FirstOrDefault() and SingleOrDefault() but that's a different question.

举个例子来说,卖场客户在不同的语言使用组合键( ID 一个表,):

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();

这code以上介绍了一种可能的逻辑错误(无从考证)。它会返回一个以上的记录(假设你有在多语言的客户记录),但它永远只返回第一个...有时候可能工作... ...而不是其他。这是联合国predictable。

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.

由于你的意图是返回一个客户使用单();

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() 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记录将有助于你避免逻辑错误。

Using Single() when you feel it should explicitly always return 1 record will help you avoid logic errors.

这篇关于LINQ单VS第一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆