balexandre
balexandre

Reputation: 75073

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?

Upvotes: 10

Views: 8324

Answers (5)

rwg
rwg

Reputation: 934

        var context = new AdventureWorksLT2008Entities();
        var cust = context.Customers.Where(c => c.CustomerID == 1);
        if (cust.Any())
        {
            Customer c = cust.First(); 
        }

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564363

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();

Upvotes: 18

MStodd
MStodd

Reputation: 4746

This will return the first one if there is one, or null if there isn't:

return (from c in db.Companies
where c.active == true && 
c.company_id == company_id
select c).FirstOrDefault();

Upvotes: 2

Gage
Gage

Reputation: 7493

Try return cmps.Count()==0?null:cmp.First()

That way if it is null it will simply return a null Company and if its not then it will return the first one in the list.

Check out http://en.wikipedia.org/wiki/Ternary_operation

Upvotes: 1

JonH
JonH

Reputation: 33143

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;

Upvotes: 5

Related Questions