How to handle null values in linq?
50,105
_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)
Author by
Gautam G
Updated on April 12, 2020Comments
-
Gautam G about 4 years
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?
-
Gautam G about 11 yearsThis extension method scheme didn't work for me, it demanded 2 arguments. But thanks for the idea. I implemented it in some other manner and got my problem resolved.
-
Zdeslav Vojkovic about 11 yearsNot sure if I understood correctly, but the first argument is
this AttendanceBAL bal
, so you still call it as if it has 1 argument:bal..GetAttendanceListOf(q._RollNumber)
. That's the whole point of extension methods