devoured elysium
devoured elysium

Reputation: 105027

LINQ -Single operator

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!

Upvotes: 3

Views: 1311

Answers (3)

James Schek
James Schek

Reputation: 17960

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
   }

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062492

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.

Upvotes: 6

Denis Troller
Denis Troller

Reputation: 7501

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.

Upvotes: 6

Related Questions