如何在LINQ中处理没有结果?

bal*_*dre 9 linq linq-to-entities nullable

在这个示例代码中

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();
}
Run Code Online (Sandbox Code Playgroud)

如果没有数据,我该如何处理cmps

cmps 永远不会为null,那么如何检查LINQ查询中的非现有数据?

所以我可以避免这种情况

'cmps.ToList()' threw an exception of type ... {System.NullReferenceException}
Run Code Online (Sandbox Code Playgroud)

将其转换为例如List时

GetCompanyById(1).ToList();
Run Code Online (Sandbox Code Playgroud)

总是需要把它包裹起来try catch吗?

Ree*_*sey 16

您可以使用Queryable.Any()(或Enumerable.Any())来查看是否有成员cmps.这将允许您进行显式检查,并根据您的意愿处理它.

如果您的目标是null在没有匹配项时返回,只需在return语句中使用FirstOrDefault而不是First:

return cmps.FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)


Jon*_*onH 5

如何申请.Any或.Count()?

这是MSDN上的一个例子

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

或者只使用?:运算符

return myExample.Any() ? myExample.First() : null;
Run Code Online (Sandbox Code Playgroud)