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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With