Sunday, March 23, 2008

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 entity
SingleOrDefault – 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


 

posted on Sunday, March 23, 2008 10:57:52 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback
Related posts:
LINQ to the Enterprise - Video on INETA LIVE
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):