Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle no results in LINQ?

in this example code

public Company GetCompanyById(Decimal company_id)
{
    IQueryable<Company> cmps = from c in db.Companies
                               where c.active == true && 
                                     c.company_id == company_id
                               select c;
    return cmps.First();
}

How should I handle if there is no data in cmps?

cmps will never be null, so how can I check for non existing data in a LINQ Query?

so I can avoid this

'cmps.ToList()' threw an exception of type ... {System.NullReferenceException}

when transforming it into, for example, a List

GetCompanyById(1).ToList();

Do I always need to wrap it up in a try catch block?

like image 905
balexandre Avatar asked Oct 07 '10 18:10

balexandre


2 Answers

You can use Queryable.Any() (or Enumerable.Any()) to see if there is a member in cmps. This would let you do explicit checking, and handle it however you wish.

If your goal is to just return null if there are no matches, just use FirstOrDefault instead of First in your return statement:

return cmps.FirstOrDefault();
like image 74
Reed Copsey Avatar answered Sep 22 '22 04:09

Reed Copsey


What about applying .Any or .Count() ?

Here's an example on MSDN

List<int> numbers = new List<int> { 1, 2 };
bool hasElements = numbers.Any();
Console.WriteLine("The list {0} empty.",
                    hasElements ? "is not" : "is");

Or just use the ?: operator

return myExample.Any() ? myExample.First() : null;
like image 38
JonH Avatar answered Sep 20 '22 04:09

JonH