tags:

views:

50

answers:

3

Hi all,

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

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;

        }

Thanks in advanced, greetings

A: 

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>();
Konamiman
A: 

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)

Benjol
I'm pretty sure your first line won't compile as it will return a single company which is not IEnumerable<Company>.
Greg Beech
A: 

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;
Greg Beech