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.
– Will return back a single entity
– 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)
- return the entity at the given index
- Returns the first entity of the collection
– 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.