List querying with Lamda Expressions in C#.NET

Posted by Pavan Kumar Pabothu on Geeks with Blogs See other posts from Geeks with Blogs or by Pavan Kumar Pabothu
Published on Thu, 17 Mar 2011 01:52:23 GMT Indexed on 2011/03/17 8:10 UTC
Read the original article Hit count: 337

Filed under:

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 });
}

© Geeks with Blogs or respective owner