C# 如何处理 linq 中的空值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15948369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to handle null values in linq?
提问by Gautam G
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
GetAttendanceListOf(q._RollNumber)
上面代码中的方法将从数据库中返回一个记录列表,或者如果传递的“roll-no”没有记录存在,则返回“null”。linq 查询将被终止并产生错误
"Value cannot be null".
“值不能为空”。
Is there a way to handle this error and make LINQ jump to next step?
有没有办法处理这个错误并使 LINQ 跳转到下一步?
采纳答案by Zdeslav Vojkovic
_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:
问题在于Where()
在空实例上运行。可能的解决方案:
1) modify GetAttendanceListOf
to return an empty list if no attendance (good idea in general, as null object patternis 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.
1) 修改GetAttendanceListOf
以在无人出席时返回一个空列表(一般来说是个好主意,因为null 对象模式通常可以挽救生命,而对于集合,空集合通常在语义上类似于 null)
2) 如果您不控制该方法,编写一个安全的扩展方法,在为空的情况下将返回空列表,例如
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)
回答by JCorriveau
Linq ToList() will return an empty list if there are no results. The error might comes from elsewhere.
如果没有结果,Linq ToList() 将返回一个空列表。错误可能来自其他地方。
I would recommand you to use methods to create your objects, it will make your query easier to read and to debug. I would recommand that you do it in multiple steps to determine what is getting null and where exactly it fails to execute.
我建议您使用方法来创建对象,这将使您的查询更易于阅读和调试。我建议您分多个步骤执行此操作,以确定什么是 null 以及它究竟在何处无法执行。
The error might comes from GetAttendanceListOf(), when having methods returning IList or IEnumerable, you should return an empty list if there is no results, it will prevent you from validating every time if it's null or not.
错误可能来自 GetAttendanceListOf(),当方法返回 IList 或 IEnumerable 时,如果没有结果,您应该返回一个空列表,它会阻止您每次验证是否为空。
回答by Cornelius
You can try
你可以试试
recordsList.ListOfRecords = new StudentRecordsBAL().GetStudentsList().Select(q =>
{
var attendanceList = new AttendanceBAL().GetAttendanceListOf(q._RollNumber);
if (attendanceList == null)
return null;
return new StudentRecords()
{
_RollNumber = q._RollNumber,
_Class = q._Class,
_Name = q._Name,
_Address = q._Address,
_City = q._City,
_State = q._State,
_Subjects = q._Subject,
_AttendedDays = attendanceList.Where(date => date != null).Select(date => new DateTime(date._Date.Year, date._Date.Month, date._Date.Day)).Distinct().ToList(),
_AttendedSubjects = GetAttendedSubjects(q._RollNumber)
};
}).Where(q => q != null).ToList();
This checks that you do not do a Where
operation on a null object and filter out any null results.
这会检查您没有Where
对空对象执行操作并过滤掉任何空结果。
回答by Eli Algranti
As suggested by @Zdeslav Vojkovic modify GetAttendanceListOf
to return empty list if null or do something like:
正如@Zdeslav Vojkovic 所建议的,GetAttendanceListOf
如果为 null则修改为返回空列表或执行以下操作:
_AttendedDays = (new AttendanceBAL() .GetAttendanceListOf(q._RollNumber) ?? Enumerator.Empty<typeofrecord>()) .Where(date => date != null) .Select(date => new DateTime(date._Date.Year, date._Date.Month, date._Date.Day)) .Distinct() .ToList(),
(you might be able to do it without the extra parenthesis)
(您可能无需额外的括号就可以做到)
回答by Mat J
For a quick fix, Modify this line
要快速修复,请修改此行
_AttendedDays = new AttendanceBAL().GetAttendanceListOf(q._RollNumber).Where...
_AttendedDays = new AttendanceBAL().GetAttendanceListOf(q._RollNumber).Where...
To this
对此
_AttendedDays = (new AttendanceBAL().GetAttendanceListOf(q._RollNumber)??new List()).Where...
_AttendedDays = (new AttendanceBAL().GetAttendanceListOf(q._RollNumber) ??new List()).Where...