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..
The major difference between First and FirstOrDefault is that First() will throw an exception if there is no result data for the supplied criteria whereas FirstOrDefault() returns a default value (null) if there is no result data.
FirstOrDefault returns the default value of a type if no item matches the predicate. For reference types that is null . Thats the reason for the exception.
Use the FirstorDefault() method to return the first element of a sequence or a default value if element isn't there. List<double> val = new List<double> { }; Now, we cannot display the first element, since it is an empty collection. For that, use the FirstorDefault() method to display the default value.
SingleOrDefault() Vs. FirstOrDefault() in LINQ QuerySingleOrDefault() – Same as Single(), but it can handle the null value. First() - There is at least one result, an exception is thrown if no result is returned. FirstOrDefault() - Same as First(), but not thrown any exception or return null when there is no result.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With