Filter out Complex List using Delegate and Lambda expression

Ssnkumar3
Posted by Ssnkumar3 under C# category on | Points: 40 | Views : 952
Create a new class and name the class as Emp. Add Empid, EmpName and Salary field to the class.


public class Emp
{
public int EmpID { get; set; }
public string EmpName { get; set; }
public int Salary { get; set; }
}


Create new aspx file. Add two buttons and name it as btnDelegate and btnLambda. Double click btnDelegate and add the below code. Make sure to select .net Framework 2.0 or above when you create the website or project.


protected void btnDelegate_Click(object sender, EventArgs e)
{
List<Emp> le=BindList();
List<Emp> lstGs = le.FindAll(delegate(Emp p) { return p.Salary > 50000; });
}

Do the same thing for btnLambda also.


protected void btnLambda_Click(object sender, EventArgs e)
{
List<Emp> le = BindList();
List<Emp> lstGs = le.FindAll(p => p.Salary > 50000);
}

The above code is very simple. But this code will only work on .net framework 3.0 or above.


Add new method to populate the Emp object.


private List<Emp> BindList()
{
return new List<Emp>() { new Emp { EmpID = 1, EmpName = "a", Salary = 50000 },
new Emp { EmpID = 2, EmpName = "b", Salary = 60000 },
new Emp { EmpID = 3, EmpName = "c", Salary = 70000 }};
}

Now click the appropriate button and view the result using immediate window or quick watch.

Comments or Responses

Login to post response