Click here to Skip to main content
Click here to Skip to main content
Technical Blog

LINQ: Single vs. First

, 13 Apr 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
LINQ: Single vs. First
LINQ With C# (Portuguese)

I've witnessed and been involved in several discussions around the correctness or usefulness of the Single method in the LINQ API.

The most common argument is that you are querying for the first element on the result set and an exception will be thrown if there’s more than one element. The First method should be used instead, because it doesn't throw if the result set has more than one item.

Although the documentation for Single states that it returns a single, specific element of a sequence of values, it actually returns THE single, specific element of a sequence of ONE value. When you use the Single method in your code you are asserting that your query will result in a scalar result instead of a result set of arbitrary length.

On the other hand, the documentation for First states that it returns the first element of a sequence of arbitrary length.

Imagine you want to catch a taxi. You go to the taxi line and catch the FIRST one, no matter how many are there.

On the other hand, if you go to the parking lot to get your car, you want the SINGLE one specific car that’s yours. If your “query” “returns” more than one car, it’s an exception. Either because it “returned” not only your car or you happen to have more than one car in that parking lot. In either case, you can only drive one car at once and you'll need to refine your “query”.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Paulo Morgado
Software Developer (Senior) Paulo Morgado
Portugal Portugal

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141223.1 | Last Updated 13 Apr 2010
Article Copyright 2010 by Paulo Morgado
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid