This is my code and I want to simplify it.
int minSalary = empList.Min(e => e.salary);
var emp = empList.Where(e => e.salary == minSalary).FirstOrDefault();
string empName = emp= != null ? emp= .Name : string.Empty;
This is my code and I want to simplify it.
int minSalary = empList.Min(e => e.salary);
var emp = empList.Where(e => e.salary == minSalary).FirstOrDefault();
string empName = emp= != null ? emp= .Name : string.Empty;
You can order the collection by the salary and then retrieving the first item is the one with the minimum salary
. Retrieve it using FirstOrDefault
and access the Name
property using ?.
operator (C# 6.0).
Last as Name
might be null
(if FirstOrDefault
returned null
) use ??
operator
string name = empList.OrderBy(e => e.salary).FirstOrDefault()?.Name ?? string.Empty;
For Prior C# 6.0:
var emp = empList.OrderBy(e => e.salary).FirstOrDefault();
var name = emp != null ? emp.Name : string.Empty;
var employeeWithMinSalary = empList.OrderBy(e => e.Salary).FirstOrDefault();
string employeeWithMinSalaryName = employeeWithMinSalary?.Name;
Sort the collection by salary and then select the employee name as follows:
var name = empList.OrderBy(e => e.salary)
.Select(e => e.Name)
.FirstOrDefault() ?? string.Empty;