Saturday, September 15, 2012

Lamda Expression based Fillter, sorting ,object Return



Here we  are discussion how to lamda expression  query to a data base object

public class customers
{
    public int customerId { get; set; }
    public string Name { get; set; }
    public decimal Salary { get; set; }
}

List<customers> customerList = new List<customers>();
List<customers> resultList = new List<customers>();
decimal maxSalary;
List<string> customerNames = new List<string>();

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Fillcustomers();
    }

    // Getting a max salary
    maxSalary = customerList.Max((emp) => emp.Salary);

    // Filtering a List
    resultList = customerList.Where((emp) => emp.Salary > 50000).ToList();

    // Sorting a List
    // To get a descending order replace OrderBy with OrderByDescending
    resultList = customerList.OrderBy<customers, decimal>((emp) => emp.Salary).ToList();

    // Get the List of customer names only
    customerNames = customerList.Select<customers, string>(emp => emp.Name).ToList();
 
    // Getting a customized object with a given list
    var customerResultSet = customerList.Select((emp) => new { Name = emp.Name, BigSalary = emp.Salary > 50000 }).ToList();
}

private void Fillcustomers()
{
    customerList.Add(new customers { customerId = 1, Name = "Shankar", Salary = 125000 });
    customerList.Add(new customers { customerId = 2, Name = "Prasad", Salary = 90000 });
    customerList.Add(new customers { customerId = 3, Name = "Mahesh", Salary = 36000 });
}

No comments:

Post a Comment