views:

56

answers:

4

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?

+2  A: 

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;
JonH
+1  A: 

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

Gage
Easier to just use FirstOrDefault(), since that's the behavior of FirstOrDefault()... Also, better to prefer "Any()" to "Count()==0", since Count() will force a full evaluation if there are many elements.
Reed Copsey
@Reed Copsey, Just saw your answer about FirstOrDefault() didn't realize thats what it did, definately useful. Your answer is the correct one. +1
Gage
+4  A: 

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();
Reed Copsey
+1  A: 

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