python
python

Reputation: 497

How to handle NULL object property with FirstOrDefault using Linq

My real application issue looks exactly like below

Employee empl = new Employee(397947, "David", "Redson", 80000);
        employees.Add(empl);
        employees.Add(new Employee(174966, "Alfred", "Swanson", 50000));
        employees.Add(new Employee(848024, "Alima", "Bieyrou", 40000));
        employees.Add(new Employee(number: 397462, fName: "Robert",
                                     lName: "Nants", salary: 30000));


string s = employees.Where(a => a.EmployeeNumber == 20000).FirstOrDefault().FirstName;

As I am using FirstOrDefault, it is throwing error when there is no matching record. If there is a matching record, I want to return the value, or else it can be null or empty..

Upvotes: 45

Views: 147772

Answers (11)

user13295451
user13295451

Reputation:

I think the easiest way is just to write the next line:

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

What the code does is: if employees isn't null, and if it found an object in the list of employees where EmployeeNumber equals 20000, and if this instance isn't null, you'll get the FisrtName property, otherwise the string firstName will be null.

Upvotes: 4

OzBob
OzBob

Reputation: 4530

A note for EFCore6+/EF7+, the Queryable.FirstOrDefault Method returns the first element of a sequence, or a default value.

NULL is no longer returned. To check for no value found:

  int e = integerReturningQuery.FirstOrDefault();
  if (e == default) //default for int is 0

Upvotes: -1

Harald Coppoolse
Harald Coppoolse

Reputation: 30512

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.

Upvotes: 64

sujith karivelil
sujith karivelil

Reputation: 29036

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;

Upvotes: 75

Hasan Fathi
Hasan Fathi

Reputation: 6106

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.

Upvotes: 11

Dulakshi Soysa
Dulakshi Soysa

Reputation: 342

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

We can use this and avoid null exceptions occurring when and object is not created.

Upvotes: 0

grek40
grek40

Reputation: 13458

You can use DefaultIfEmpty. Consider the following example:

var entries = new Employee[0];
var result = entries.DefaultIfEmpty(new Employee() { FirstName = "<default name>" }).First().FirstName;

Upvotes: 5

Hari Prasad
Hari Prasad

Reputation: 16976

If you are sure you've only one record for a given EmployeeNumber you could use SingleOrDefault extension.

var item = employees.SingleOrDefault(a => a.EmployeeNumber == 20000);
string s = "";

if(item!= null)
{
    s = item.FirstName;
    // your logic ... 
}

In case if you have multiple records for given employeenumber, use FirstOrDefault but do null check before accessing properties.

var item = employees.FirstOrDefault(a => a.EmployeeNumber == 20000);

string s = "";    
if(item!= null)
{
    s = item.FirstName;
    // your logic ... 
}

Upvotes: 3

Vivek.Shr
Vivek.Shr

Reputation: 1

Assign value after checking if the object is null.

var emp = employees.Where(a => a.EmployeeNumber == 20000).FirstOrDefault();

string s = emp == null ? string.Empty: emp.FirstName;

Upvotes: 0

harishr
harishr

Reputation: 18065

you can do like below

var employee = employees.FirstOrDefault(a => a.EmployeeNumber == 20000);
return employee != null ? employee.Name : string.Empty;

Upvotes: 1

Ash
Ash

Reputation: 2605

May be you can try using null propagation to make it easier:

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

Upvotes: 10

Related Questions