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;

        }

3 Answers 3

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)

Sign up to request clarification or add additional context in comments.

1 Comment

I'm pretty sure your first line won't compile as it will return a single company which is not IEnumerable<Company>.
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>();

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.