开发者

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 nev开发者_开发知识库er 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?


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


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;


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜