How to handle NULL object property with FirstOrDefault using Linq
Select the string in your linq statement before your FirstOrDefault and you get your string or the default string:
string s = employees.Where(a => a.EmployeeNumber == 2000)
.Select(a => a.FirstName)
.FirstOrDefault();
This has the advantage that only the value that you will be using will be fetched, not the complete Employee.
In C# 8
and later use the null-coalescing
operator ??
and null checking operator ?
.
Like this:
string s = employees?.Where(a => a.EmployeeNumber == 20000)
.FirstOrDefault()?
.FirstName ?? string.Empty;
To avoid any null exceptions in the employees
list and any employee properties.
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;
May be you can try using null propagation to make it easier:
string s = employees.Where(a => a.EmployeeNumber == 20000).FirstOrDefault()?.FirstName;