LINQ is the only statement

I read about this statement in a book, but since I do not use such databases, I cannot think of any call where I want to get one element. I mean, I can have many conditions, but then I will use First or Last, and not Single. What is the difference? What is the point of returning only one element and throwing an exception if there are no results or more than one? The only thing that comes to my mind is to make sure that there really is only one element.

Thanks!

+3
source share
3 answers

. , -, , , .

+6

, id ( , , , id):

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

SingleOrDefault, ( , null), 2 ( ), , .

+6

LINQ . factory . , (, , ). LINQ (, , ) .

:

   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
   }
+1

Source: https://habr.com/ru/post/1714845/


All Articles