如何在linq中处理空值

如何在linq中处理空值

本文介绍了如何在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();

上面的代码中的方法 GetAttendanceListOf(q._RollNumber) 将返回数据库中的记录列表,如果没有传递的"roll-no"记录,则返回"null". linq查询将终止,并产生错误

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

有没有办法处理此错误并使LINQ跳到下一步?

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

推荐答案

_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(),

问题在于在空实例上运行Where().可能的解决方案:

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

1)修改GetAttendanceListOf,以在没有出席的情况下返回一个空列表(通常是一个好主意,如空对象模式通常是救命稻草,对于集合来说,空集合在语义上通常类似于null)
2)如果您不控制该方法,请编写一个安全的扩展方法,该方法将在null的情况下返回空列表,例如

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>();
}

然后将其称为:

_AttendedDays = new AttendanceBAL()
    .SafeAttendanceListOf(q._RollNumber)
    .Where(date => date != null)

这篇关于如何在linq中处理空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 06:36