LINQ where子句和计算结果的空异常 [英] linq where clause and count result in null exception

查看:1024
本文介绍了LINQ where子句和计算结果的空异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码工作,除非p.School.SchoolName原来是空,在这种情况下,它会导致一个NullReferenceException。

 如果(ExistingUsers.Where(p => p.StudentID == item.StaffID&放大器;&安培; 
p.School.SchoolName == item.SchoolID).Count之间的()0)
{
//做的东西。
}



ExistingUsers是用户的列表:

 公开名单<使用者> ExistingUsers; 

下面是堆栈跟踪的相关部分:




System.NullReferenceException:未将对象引用设置到对象的实例



在System.Linq.Enumerable.WhereListIterator 在System.Linq.Enumerable.Count [TSource] 1.MoveNext()结果
(IEnumerable的
1源)




我应该如何处理这个where子句?



在此先感谢非常多。


< DIV CLASS =h2_lin>解决方案

我怀疑 p.School 为空,而不是 SchoolName 。只需访问 SchoolName 前添加一个空检查。此外,使用任何()来检查是否有任何结果,而不是计数()> 0 除非你有需要的计数真的。这将执行更好,因为如果存在任何并非所有的项目迭代

  VAR的结果= ExistingUsers.Where(P =方式>页。 StudentID == item.StaffID 
和;&安培; p.School = NULL
和!&安培; p.School.SchoolName == item.SchoolID)
。任何();

如果(结果){/ *做某事* /}


The code below works unless p.School.SchoolName turns out to be null, in which case it results in a NullReferenceException.

if (ExistingUsers.Where(p => p.StudentID == item.StaffID &&
                        p.School.SchoolName == item.SchoolID).Count() > 0)
{
    // Do stuff.
}

ExistingUsers is a list of users:

public List<User> ExistingUsers;

Here is the relevant portion of the stacktrace:

System.NullReferenceException: Object reference not set to an instance of an object.

at System.Linq.Enumerable.WhereListIterator1.MoveNext()
at System.Linq.Enumerable.Count[TSource](IEnumerable
1 source)

How should I handle this where clause?

Thanks very much in advance.

解决方案

I suspect p.School is null, not SchoolName. Simply add a null check before accessing SchoolName. Also, use Any() to check if there are any results instead of Count() > 0 unless you're really in need of the count. This performs better since not all items are iterated if any exist.

var result = ExistingUsers.Where(p => p.StudentID == item.StaffID
                            && p.School != null
                            && p.School.SchoolName == item.SchoolID)
                         .Any();

if (result) { /* do something */ }

这篇关于LINQ where子句和计算结果的空异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆