tags:

views:

181

answers:

3

Hello. I've read about this operator on a book but being that I don't use databases that much, I cannot think of any circunstance where I'd want to get a single item. I mean, I can have a set of conditions, but then I'd use First or Last, not Single. What is the difference? What is the point of having it return just a single item, and throwing an exception if there are no results or more than one? Only thing that comes to my mind would be to make sure there is really just one item.

Thanks!

+6  A: 

This is exactly why you'd want that. Sometimes, having more than one item in the result set indicates a bug somewhere and you'd like an exception to be thrown if that is not the case.

Denis Troller
Ah, so that is the only case where you'd want that?
devoured elysium
+5  A: 

The classic example here is when you have an id (and so expect the data to exist, uniquely, by that id):

var item = ctx.SomeTable.Single(x=>x.Id == id);

You could check SingleOrDefault if useful (to give a better error message if you get a null), but getting 2 (or more) is definitely a big problem.

Marc Gravell
+1 good example.
Meta-Knight
+1  A: 

The LINQ extensions are useful outside of databases as well. An actual example was to find the correct factory from a framework for a given input string. If the input string matched multiple factories, that was considered an error (or at least needed special case handling). I've also used LINQ (and single in particular) for building unit tests.

Example:

   try {
      IWorkspaceFactory factories[] = { 
         new SdeFactory(), new FGDBFactory(), new AccessFactory() };
      IWorkspace workspace = factories
         .Single(wf=>wf.IsWorkspace(input)).Open(input);
      workspace.DoSoething();
   } catch(OperationException) {
      //can't remember the exact exception off the top of my head
      //Catch more than one match
   }
James Schek