0

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;
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
pandu m
  • 3
  • 1

3 Answers3

2

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;
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
1
var employeeWithMinSalary = empList.OrderBy(e => e.Salary).FirstOrDefault();
string employeeWithMinSalaryName = employeeWithMinSalary?.Name;
DDan
  • 8,068
  • 5
  • 33
  • 52
1

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;
ashin
  • 2,543
  • 1
  • 12
  • 17