How to handle NULL object property with FirstOrDefault using Linq

You need not use Where and the FirstOrDefault in this case, you can specify the filter condition inside the FirstOrDefault itself. But which will give you null if there are no records satisfying the condition(because in the absence of the first value it will give you the default value, for reference type objects the default value is null), you should check for null before accessing the value, which will throws NullReferenceException. So Use like this:

var Employee=employees.FirstOrDefault(a => a.EmployeeNumber == 20000);
if(Employee!=null)
{
  string employee_name=Employee.FirstName;
  // code here
}

Or else you can use ?. to check for null like this:

string employee_name = employees.FirstOrDefault(a => a.EmployeeNumber == 20000)?.FirstName;

Leave a Comment