Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice of SingleOrDefault()

Tags:

c#

linq-to-sql

I want to make my code better. Can I safely 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 not being clear. My issue is to get the PDF object out directly without having to use a list first. I don't want to make a check for count is greater than 0 and because it just doesn't look good.

like image 626
radbyx Avatar asked Dec 01 '22 04:12

radbyx


2 Answers

Yes, that looks safe. You can also simplify your query slightly:

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

The only difference between SingleOrDefault and FirstOrDefault is that SingleOrDefault will throw an exception if more than one match is found, so unless you want this check then you may as well stick to FirstOrDefault.

like image 57
MarkXA Avatar answered Dec 03 '22 18:12

MarkXA


You should use FirstOrDefault in the second case too as SingleOrDefault will throw an exception if there is more than one item. Is that ok for you?

On the other hand if you want to guarantee that there is only one pdfobject for some id than using SignleOrDefault is better.

like image 42
Giorgi Avatar answered Dec 03 '22 18:12

Giorgi