LIST Search using Anonymous Methods

An Anonymous method is a new feature introduced in C# 2.0 to have methods without name. which can help increase the readability and maintainability of your applications by keeping the caller of the method and the method itself as close to one another as possible. Prior to C# 2.0, a developer would have to define a separate method when needing to execute a callback using a delegate. But in C# 2.0 Anonymous method uses the keyword, delegate, instead of a method name and contain the body of the method.

Following sample code contains a C# List Searching and filtering technique by using Anonymous method.

public class Employee
{
private string name;
private double salary;

public string Name
{
get { return name; }
set { name = value; }
}

public double Salary
{
get { return salary; }
set { salary = value; }
}
}

Employee emp1 = new Employee();
emp1.Name = "Jeff";
emp1.Salary = 200000.00;

Employee emp2 = new Employee();
emp2.Name = "Anne";
emp2.Salary = 500000.00;

Employee emp3 = new Employee();
emp3.Name = "Jane";
emp3.Salary = 900000.00;

List empList = new List();
empList.Add(emp1);
empList.Add(emp2);
empList.Add(emp3);

//Search the Employees those salaries are larger than specified value.
List newEmpList = new List(empList).FindAll(
delegate(Employee emp)
{
return emp.Salary > 400000.00;
}
);

No comments:

Post a Comment