LINQ: Single vs. First

Posted by Paulo Morgado on ASP.net Weblogs See other posts from ASP.net Weblogs or by Paulo Morgado
Published on Sun, 28 Mar 2010 22:46:28 GMT Indexed on 2010/03/28 22:53 UTC
Read the original article Hit count: 691

Filed under:
|
|
|

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. One 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 the the taxi line and catch the FIRST one, no matter how many are there.

On the other hand, if you go the 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”.

© ASP.net Weblogs or respective owner

Related posts about .NET

Related posts about LINQ