isshin
isshin

Reputation: 91

Null check nested lambda

I'm currently using a lambda to set a property.

Team = department.Teams
                 .Where( t => t.GUID == a.Personnel.Roles
                        .Where(r=>r.Department==department && r.EndDate==null)
                        .SingleOrDefault()
                        .DeptTeamGUID)
                 .FirstOrDefault().Name

Department has a bunch of teams. A personnel has a role that is connected to that team. The PersonnelRole contains data about the department and which team the role is a part of.

However sometimes a personnel can have a role with no team. In this case I get a "Object reference not set to an instance of an object." exception.

I have also tried to modify the lambda to filter out Roles that doesn't have a DeptTeamGUID, but my logic seems off.

Team = department.Teams
                 .Where( t => t.GUID==a.Personnel.Roles
                         .Where( r => r.Department==department && r.EndDate==null 
                                      && r.DeptTeamGUID !=null)
                         .SingleOrDefault().DeptTeamGUID)
                 .FirstOrDefault().Name

Can anyone guide me in the right direction?

Upvotes: 0

Views: 365

Answers (1)

Maarten
Maarten

Reputation: 22945

You are getting the null-reference exception because you are trying to read a property from a null-reference, when you are doing it using the construct .SingleOrDefault().PropertyName.

You have to change .SingleOrDefault().PropertyName to .Select(x => x.PropertyName).SingleOrDefault(), like this:

Team = department.Teams
    .Where(t => t.GUID == a.Personnel.Roles
        .Where(r => r.Department == department && r.EndDate == null)
        .Select(x => x.DeptTeamGUID)
        .SingleOrDefault()
    )
    .Select(x => x.Name)
    .FirstOrDefault();

Note: this should make it work, but since t.Guid == null is not true, your case of personnel with no team will not be returned by the query.

Another note: I suspect that you might miss some results that you would normally expect, since you are using the .SingleOrDefault() in your subquery. Perhaps you should use .Contains(...) to check all guid's. Like this:

Team = department.Teams
    .Where(t => a.Personnel.Roles
        .Where(r => r.Department == department && r.EndDate == null)
        .Select(x => x.DeptTeamGUID)
        .Contains(t.GUID)
    )
    .Select(x => x.Name)
    .FirstOrDefault();

Upvotes: 3

Related Questions