Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq where clause and count result in null exception

Tags:

c#

linq

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.

like image 786
IntrepidDude Avatar asked Mar 23 '10 04:03

IntrepidDude


2 Answers

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 */ }
like image 88
Ahmad Mageed Avatar answered Sep 22 '22 00:09

Ahmad Mageed


For all database nullable columns, we should either add null check or do simple comparision a == b instead of a.ToLower() == b.ToLower() or similar string operations.
My observation as below:
As they get iterated through Enumerable of LINQ Query for comparision against with input string/value, any null value (of database column) and operations on it would raise exception, but Enumerable becomes NULL, though query is not null.

like image 43
Hydtechie Avatar answered Sep 21 '22 00:09

Hydtechie