我有这个代码。如何使用SingleOrDefault方法检查空值?
public static List<ETY.Rol> GetRolesByApplicationAndCompany(this UsuarioContext usuario, int company, int app)
{
List<ETY.Company> lCompanies= usuario.Companies;
var roles = lCompanies.
SingleOrDefault(e => (e.Id == company)).Applications.
SingleOrDefault(a => a.Id == app).Roles;
return roles;
}
答案 0 :(得分:1)
您可以尝试查看Maybe / IfNotNull扩展方法(here和here)。
或者使用类似这样的Linq语法(未经测试):
var q = from company in lCompanies.SingleOrDefault(e => e.Id == company)
where company != null
let application = company.Applications.SingleOrDefault(a => a.Id == app)
where application != null
select application.Roles;
(如果保证单一条件,Greg Beech's answer会更好)
答案 1 :(得分:0)
如果SingleOrDefault
中的任何一个返回null,是指返回null还是空列表?在那种情况下:
var company = lCompanies.SingleOrDefault(e => (e.Id == company));
if(company != null) {
var application = company.Applications.SingleOrDefault(a => a.Id == app);
if(application!=null) {
return application.Roles;
}
}
return null; //Or: return new List<ETY.Rol>();
答案 2 :(得分:0)
您可以按如下方式编写链式查询,而不是使用SingleOrDefault
。你失去了确保只有一个应用程序或公司的语义,但如果你知道总是如此,那么它应该不是问题。
return from c in lCompanies where c.Id == company
from a in c.Applications where a.Id == app
select a.Roles;