45

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..

3
  • 2
    Why not just check if return value is not null before accessing the FirstName property? Jul 21, 2016 at 5:37
  • Are you wanting SingleOrDefault(). Jul 21, 2016 at 5:38
  • Ii think FirstOrDefault is best option see answer of @hariprasad
    – Eldho
    Jul 21, 2016 at 6:06

11 Answers 11

74

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;
2
  • 3
    This method is not efficient. FirstOrDefault retrieves the complete Employee to local after which you throw away most fields. Use your SQL server profiler to check the SQL statement. Jul 21, 2016 at 10:19
  • 5
    The null-propagating operator ?. (aka Elvis operator) is not allowed in a queryable (LINQ-to-SQL or LINQ-to-Entities) collection. However, it works fine for a LINQ-to-Objects collection.
    – Suncat2000
    Aug 29, 2019 at 20:12
63

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.

6
  • 10
    Hmm, I'm wondering why this most natural solution is totally ignored. +1
    – Ivan Stoev
    Jul 21, 2016 at 9:51
  • Putting the FirstOrDefault at the end will often mean that the entire result is loaded into memory before the first element is selected. Replacing the Where with the FirstOrDefault will cause the underlying query to implement the selection as a Top 1. This boils down to differences in the implementation of the underlying LINQ provider. Apr 24, 2018 at 22:17
  • 1
    I don't agree. FirstOrDefault does not load the entire collection. According to the reference source. It gets the enumerator, does ONE MoveNext and returns the Current. See github.com/Microsoft/referencesource/blob/master/System.Core/… Apr 25, 2018 at 6:31
  • For IQueryable it depends on the class that holds Queryable.Expression. Entity Framework DbSet class makes it a SQL "Select Top 1 ..." So also for IQueryable I don't see any evidence that the complete collection is downloaded. Apr 25, 2018 at 6:37
  • 5
    This should be the accepted answer, more clear, shorter, and less data transferred in the majority case. May 30, 2018 at 20:20
10

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

string s = employees.Where(a => a.EmployeeNumber == 20000).FirstOrDefault()?.FirstName;
3
  • 6
    worth to mention that the null propagation operator only works in C# 6+
    – fubo
    Jul 21, 2016 at 5:50
  • 3
    @fubo C#6 is the current version of C#, I don't see why we need to mention that. We don't do that for other C# versions.
    – Ivan Stoev
    Jul 21, 2016 at 9:48
  • 4
    As I commented earlier, this is not allowed in a queryable (LINQ-to-SQL or LINQ-to-Entities) collection because the operator is not translated. @Ivan Stoev We do mention C# versions in other answers where a behavior is not implemented in earlier versions. It's usually mentioned where only some versions support the operation being discussed.
    – Suncat2000
    Aug 29, 2019 at 20:20
9

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.

5

You can use DefaultIfEmpty. Consider the following example:

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

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.

3

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 ... 
}
4
  • And how is he supposed to use variable s outside your if block?
    – Ash
    Jul 21, 2016 at 5:41
  • there is a chance for multiple records, can use in the below way if (employees.Where(a => a.EmployeeNumber == 397947).FirstOrDefault() != null) { string s = employees.Where(a => a.EmployeeNumber == 397947).FirstOrDefault().FirstName; }
    – python
    Jul 21, 2016 at 5:46
  • In that case use the second approach. Jul 21, 2016 at 5:47
  • @fubo Updated it. Thanks. Jul 21, 2016 at 5:51
1

you can do like below

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

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;
3
  • 3
    What is the need for Where, you can specify the condition inside the FirstOrDefault Jul 21, 2016 at 5:44
  • instead of var can use like the below if (employees.Where(a => a.EmployeeNumber == 397947).FirstOrDefault() != null) { string s = employees.Where(a => a.EmployeeNumber == 397947).FirstOrDefault().FirstName; }
    – python
    Jul 21, 2016 at 5:47
  • @python : why would you execute the same expression two times just for checking null condition? It's better to store the result in a variable and then check the value of the variable. DRY principle- Don't Repeat Yourself.
    – Vivek.Shr
    Jul 22, 2016 at 7:47
0
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.

-1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.