List querying with Lamda Expressions in C#.NET
- by Pavan Kumar Pabothu
public class Employees
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public decimal Salary { get; set; }
}
List<Employees> employeeList = new List<Employees>();
List<Employees> resultList = new List<Employees>();
decimal maxSalary;
List<string> employeeNames = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillEmployees();
}
// Getting a max salary
maxSalary = employeeList.Max((emp) => emp.Salary);
// Filtering a List
resultList = employeeList.Where((emp) => emp.Salary > 50000).ToList();
// Sorting a List
// To get a descending order replace OrderBy with OrderByDescending
resultList = employeeList.OrderBy<Employees, decimal>((emp) => emp.Salary).ToList();
// Get the List of employee names only
employeeNames = employeeList.Select<Employees, string>(emp => emp.Name).ToList();
// Getting a customized object with a given list
var employeeResultSet = employeeList.Select((emp) => new { Name = emp.Name, BigSalary = emp.Salary > 50000 }).ToList();
}
private void FillEmployees()
{
employeeList.Add(new Employees { EmployeeId = 1, Name = "Shankar", Salary = 125000 });
employeeList.Add(new Employees { EmployeeId = 2, Name = "Prasad", Salary = 90000 });
employeeList.Add(new Employees { EmployeeId = 3, Name = "Mahesh", Salary = 36000 });
}