Best Practice SingleOrDefault ()

I want to improve my code. Is it safe to rewrite the first example to the second?

IQueryable<PDF> pdfList = (from pdfobj in pdfDataContext.PDFs where pdfobj.Id == pdfId select pdfobj); if (pdfList.Count() > 0) { PDF pdfOldWay = pdfList.FirstOrDefault(); pdfOldWay. // do something. (pdfOldWay can't be null here...) } 

-

 PDF pdfNewWay = (from pdfobj in pdfDataContext.PDFs where pdfobj.Id == pdfId select pdfobj).SingleOrDefault(); if (pdfNewWay != null) { // do something } 

-

EDIT:

Sorry for what you did not understand. My problem is to get the PDF object directly without using the list first. I don’t want to check to count more than 0, and because it just doesn’t look good.

+4
source share
4 answers

Yes, it looks safe. You can also simplify your query a bit:

 PDF pdfNewWay = pdfDataContext.PDFs.SingleOrDefault(p => p.Id == pdfId); if (pdfNewWay != null) { // do something } 

The only difference between SingleOrDefault and FirstOrDefault is that SingleOrDefault throws an exception if more than one match is found, so if you do not want this check, you can also stick to FirstOrDefault.

+10
source

You should use FirstOrDefault in the second case, since SingleOrDefault will throw an exception if there is more than one element. Is it OK for you?

On the other hand, if you want to guarantee that for some id there is only one pdf object, the better to use SignleOrDefault.

+6
source

If it guarantees that it always has 0 or 1 row, then necessarily, SingleOrDefault is the best solution.

+3
source

Yes, you will achieve the same result, I do not see any problem.

0
source

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


All Articles