开发者

Why do we need Single() in LINQ?

Why is the mai开发者_开发知识库n purpose of the extension method 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.


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.

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. The rest of the elements are of no consequence. On the other hand Single must consider the entire enumeration. If multiple matches are of no consequence to your program and indicate no programming errors then yes use First.


Using Single allows you to document your expectations on the number of results, and to fail early, fail hard if they are wrong. 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>. 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. An example would be a 1:1 ID:Name mapping in a database.


A Single will return a single instance of the class/object and not a collection. Very handy when you get a single record by Id. I never expect more than one row.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜