2024-11-09 05:00:06

LINQ单对第一

LINQ:

当我确定查询将返回一条记录时,使用Single()操作符比First()更有效吗?

有区别吗?


当前回答

如果不特别希望在有多个项的事件中抛出异常,请使用First()。

两者都很有效率,就拿第一项来说。First()的效率稍微高一些,因为它不需要检查是否有第二个项。

唯一的区别是,Single()期望枚举中只有一个项开始,如果有多个项,则会抛出异常。如果您特别希望在这种情况下抛出异常,则使用. single()。

其他回答

他们是不同的。它们都断言结果集不是空的,但single也断言结果集不超过1个。我个人在只希望有1个结果的情况下使用Single,因为返回超过1个结果是一个错误,可能应该这样对待。

单()

返回查询的单个特定元素 When Use:如果恰好需要1个元素;不是0或大于1。如果列表为空或包含多个元素,则会抛出异常"Sequence contains more than one element"

SingleOrDefault ()

返回查询的单个特定元素,如果没有找到结果,则返回默认值 当使用:当需要0或1个元素时。如果列表有2个或更多项,它将抛出异常。

第()

返回带有多个结果的查询的第一个元素。 When Use:当需要1个或多个元素,而您只需要第一个元素时。如果列表中不包含元素,它将抛出异常。

FirstOrDefault ()

Returns the first element of a list with any amount of elements, or a default value if the list is empty. When Use: When multiple elements are expected and you want only the first. Or the list is empty and you want a default value for the specified type, the same as default(MyObjectType). For example: if the list type is list<int> it will return the first number from the list or 0 if the list is empty. If it is list<string>, it will return the first string from the list or null if the list is empty.

如果我回忆,Single()检查在第一个元素之后是否有另一个元素(如果是这样,则抛出异常),而first()在得到它之后停止。如果序列为空,两者都会抛出异常。

就我个人而言,我总是使用First()。

如果不特别希望在有多个项的事件中抛出异常,请使用First()。

两者都很有效率,就拿第一项来说。First()的效率稍微高一些,因为它不需要检查是否有第二个项。

唯一的区别是,Single()期望枚举中只有一个项开始,如果有多个项,则会抛出异常。如果您特别希望在这种情况下抛出异常,则使用. single()。

关于性能:我和一个同事正在讨论Single vs First(或SingleOrDefault vs FirstOrDefault)的性能,我认为First(或FirstOrDefault)会更快并提高性能(我都是关于让我们的应用程序运行得更快)。

I’ve read several posts on Stack Overflow that debate this. Some say there are small performance gains using First instead of Single. This is because First would simply return the first item while Single must scan all the results to make sure there isn’t a duplicate (ie: if it found the item in the first row of the table, it still would scan every other row to make sure there isn’t a second value matching the condition which would then throw an error). I felt like I was on solid ground with “First” being faster than “Single” so I set out to prove it and put the debate to rest.

我在我的数据库中设置了一个测试,并添加了1,000,000行 ID UniqueIdentifier 外国UniqueIdentifier 信息nvarchar(50)(用数字“0”到“999,9999”的字符串填充)

我加载了数据,并将ID设置为主键字段。

使用LinqPad,我的目标是展示如果你使用Single在“Foreign”或“Info”上搜索一个值,它会比使用First差得多。

我无法解释我得到的结果。在几乎所有情况下,使用Single或SingleOrDefault略快一些。这对我来说没有任何逻辑意义,但我想分享一下。

例:我使用了以下查询:

var q = TestTables.First(x=>x.Info == "314638") ;
//Vs.
Var q = TestTables.Single(x=>x.Info =="314638") ; //(this was slightly faster to my surprise)

我在“外”键字段上尝试了类似的查询,没有索引,认为这将证明第一是更快的,但在我的测试中,单一总是略快。