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..
You need not to 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 first value it will give you the default value, for reference type objects the default value is null
), you 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 will not transfer the complete employee to local, but only the FirstName, which is the only field you want.