开发者

How to check for nulls using LINQ

I have this code. How can I check for null values with the SingleOrDefault method?

public static List<ETY.Rol> GetRolesByApplicationAndCompany(this UsuarioContext usuario, int company, int app)
        {
            List<ETY.Company> lCompanies= usuario.Compa开发者_如何学JAVAnies;

            var roles = lCompanies.
                SingleOrDefault(e => (e.Id == company)).Applications.
                SingleOrDefault(a => a.Id == app).Roles;
            return roles;

        }


You could try looking at a Maybe/IfNotNull extension method (here and here).

Or use Linq syntax something like this (untested):

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 is better if the Single condition is guaranteed)


Do you mean returning null or an empty list if any of the SingleOrDefault returns null? In that case:

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


Rather than using SingleOrDefault you could write a chained query as follows. You lose the semantics of ensuring that there's only a single application or company, but if you know that to always be the case then it shouldn't be a problem.

return from c in lCompanies where c.Id == company
       from a in c.Applications where a.Id == app
       select a.Roles;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜