At my last talk I had the following question.
"When returning a LINQ entity using the .Single() extension, what would happen if the result returned more than one row?"
The simple answer of course was that it would throw an exception, but I told him I would elaborate in a blog post. So here it is. Most LINQ queries will return an IEnumerable collection of objects as the result of your LINQ query. In order to only return a single entity, you have a couple of options.
Single – Will return back a single entitySingleOrDefault – Will return back a single entity or a Default if nothing is found
Both of these will throw an InvalidOperationException if the query returns more than one row.
If you know that your query may return more than one record, you can use the following Extension methods to return a single entity from a collection of entities. (or the OrDefault versions)
ElementAt - return the entity at the given index
First - Returns the first entity of the collection
Last – Returns the last entity in the collection.
Finally, you can also pass a predicate (a condition) as a parameter.
Here we are looking for the first publisher in the pubisher collecdtion that has a country of USA.
Hope that helps.
Happy Programming
Doc
Remember Me
Page rendered atMonday, May 12, 2008 10:36:51 AM (GMT Daylight Time, UTC+01:00)
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.