下面的代码工作,除非p.School.SchoolName原来是空,在这种情况下,它会导致一个NullReferenceException。LINQ where子句和计数结果无效例外
if (ExistingUsers.Where(p => p.StudentID == item.StaffID &&
p.School.SchoolName == item.SchoolID).Count() > 0)
{
// Do stuff.
}
ExistingUsers是用户的列表:
public List<User> ExistingUsers;
这里是堆栈跟踪的相关部分:
System.NullReferenceException:未设置为一个对象的实例对象引用。
在System.Linq.Enumerable.WhereListIterator
1.MoveNext()
1源)
at System.Linq.Enumerable.Count[TSource](IEnumerable
我应该如何处理这个where子句?
非常感谢。
你确定它的SchoolName是零,而不是p.School? – 2010-03-23 04:13:22
作为一般说明,而不是IEnumerable.Count(谓词)> 0,使用IEnumerable.Any(谓词)。这将终止第一场比赛的执行,可能会产生很大的加速。 – recursive 2010-03-23 04:16:48
@Anthony:非常感谢,我认为你是正确的p.School是空的。 – IntrepidDude 2010-03-23 04:35:02