Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle null values in linq?

recordsList.ListOfRecords = new StudentRecordsBAL()
                                .GetStudentsList()
                                .Select(q => new StudentRecords()
            {
                _RollNumber = q._RollNumber,
                _Class = q._Class,
                _Name = q._Name,
                _Address = q._Address,
                _City = q._City,
                _State = q._State,
                _Subjects = q._Subject,
                _AttendedDays = new AttendanceBAL()
                                    .GetAttendanceListOf(q._RollNumber)
                                    .Where(date => date != null)
                                    .Select(date => 
                                        new DateTime(date._Date.Year, date._Date.Month, date._Date.Day))
                                    .Distinct()
                                    .ToList(),
                _AttendedSubjects = GetAttendedSubjects(q._RollNumber)                                            
        }).ToList(); 

The method, GetAttendanceListOf(q._RollNumber) in above code will return a list of records from the database or "null" if there are no records present for the passed "roll-no". A linq query will be terminated generating error

"Value cannot be null".

Is there a way to handle this error and make LINQ jump to next step?

like image 383
Gautam G Avatar asked Apr 11 '13 12:04

Gautam G


1 Answers

_AttendedDays = new AttendanceBAL()
    .GetAttendanceListOf(q._RollNumber)
    .Where(date => date != null)
    .Select(date => new DateTime(date._Date.Year, date._Date.Month, date._Date.Day))
    .Distinct()
    .ToList(),

The problem is with running Where() on null instance. Possible solutions:

1) modify GetAttendanceListOf to return an empty list if no attendance (good idea in general, as null object pattern is very often a life saver, and for collection, an empty collection is often semantically similar to null)
2) if you don't control that method, write a safe extension method which will return empty list in case of null, e.g.

List<AttendanceType> SafeAttendanceList(this AttendanceBALType bal, RollNumber rn)
{
    return bal.GetAttendanceListOf(rn) ?? new List<AttendanceType>();
}

Then call it as:

_AttendedDays = new AttendanceBAL()
    .SafeAttendanceListOf(q._RollNumber)
    .Where(date => date != null)
like image 68
Zdeslav Vojkovic Avatar answered Nov 19 '22 00:11

Zdeslav Vojkovic