简体   繁体   English

为什么在LINQ中需要Single()?

[英]Why do we need Single() in LINQ?

Why is the main purpose of the extension method Single() ? 为什么扩展方法Single()的主要目的是什么?

I know it will throw an exception if more than an element that matches the predicate in the sequence, but I still don't understand in which context it could be useful . 我知道,如果有多个元素与序列中的谓词相匹配,它将引发异常,但是我仍然不明白在什么情况下它可能有用

Edit: 编辑:
I do understand what Single is doing, so you don't need to explain in your question what this method does. 我确实了解Single在做什么,因此您无需在问题中解释此方法的作用。

It's useful for declaratively stating 对于声明式声明很有用

I want the single element in the list and if more than one item matches then something is very wrong 我想要列表中的单个元素,如果有多个匹配项,那么很不对劲

There are many times when programs need to reduce a set of elements to the one that is interesting based an a particular predicate. 很多时候,程序需要将一组元素简化为一个基于特定谓词的有趣元素。 If more than one matches it indicates an error in the program. 如果多个匹配,则表明程序中有错误。 Without the Single method a program would need to traverse parts of the potentially expensive list more once. 如果没有“ Single方法,则程序将需要遍历部分潜在的昂贵列表一次。

Compare 比较

Item i = someCollection.Single(thePredicate);

To

Contract.Requires(someCollection.Where(thePredicate).Count() == 1);
Item i = someCollection.First(thePredicate);

The latter requires two statements and iterates a potentially expensive list twice. 后者需要两个语句,并两次迭代一个潜在的昂贵列表。 Not good. 不好。

Note: Yes First is potentially faster because it only has to iterate the enumeration up until the first element that matches. 注意:Yes First 可能会更快,因为它只需要迭代枚举直到第一个匹配的元素。 The rest of the elements are of no consequence. 其余元素无关紧要。 On the other hand Single must consider the entire enumeration. 另一方面, Single必须考虑整个枚举。 If multiple matches are of no consequence to your program and indicate no programming errors then yes use First . 如果多个匹配对您的程序没有影响,并且指示没有编程错误,请使用First

Using Single allows you to document your expectations on the number of results, and to fail early, fail hard if they are wrong. 使用Single可让您记录对结果数量的期望,并尽早失败,如果结果不正确则很难失败。 Unless you enjoy long debugging sessions for their own sake, I'd say it's enormously useful for increasing the robustness of your code. 除非您出于自己的利益而享受长时间的调试会话,否则我会说这对于提高代码的健壮性非常有用。

Every LINQ operator returns a sequence, so an IEnumerable<T> . 每个LINQ运算符都返回一个序列,因此是IEnumerable<T> To get an actual element, you need one of the First , Last or Single methods - you use the latter if you know for sure the sequence only contains one element. 要获取实际元素,您需要使用FirstLastSingle方法之一-如果您确定序列仅包含一个元素,则可以使用后者。 An example would be a 1:1 ID:Name mapping in a database. 一个示例是数据库中的1:1 ID:Name映射。

A Single will return a single instance of the class/object and not a collection. Single将返回类/对象的单个实例,而不是集合。 Very handy when you get a single record by Id. 当您获得ID的单个记录时非常方便。 I never expect more than one row. 我从未期望超过一排。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM