1

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.Companies;

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

        }
numaroth
  • 1,295
  • 4
  • 25
  • 36
Alhambra Eidos
  • 1,515
  • 4
  • 21
  • 31

3 Answers3

1

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)

Community
  • 1
  • 1
Benjol
  • 63,995
  • 54
  • 186
  • 268
0

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
  • 49,681
  • 17
  • 108
  • 138
0

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
  • 133,383
  • 43
  • 204
  • 250