Hi, IN this code snippet, you will be learning how to use the anonymous method with the help of delegates. In my case i'm taking a simple example. I have a class Employee as given below.
public class Employee { public Employee() {
} public Employee(int number, string name) { this._employeeNo = number; this._employeeName = name; } int _employeeNo; string _employeeName;
public int EmployeeNo { get { return _employeeNo; } set { _employeeNo = value; } }
public string EmployeeName { get { return _employeeName; } set { _employeeName = value; } } }
I'm createing a collection of Employee object and i will add it to the Generic List as give below.
List employees = new List(); employees.Add(new Employee(1, "Venkatarajan")); employees.Add(new Employee(2, "Siva")); employees.Add(new Employee(3, "Yogananthan")); employees.Add(new Employee(4, "Senthilkumaran")); employees.Add(new Employee(5, "Gopinath"));
Now will look how the delegate can be used to find a Employee object in this collection. My Scenario is, i need to find a Employee object whose Employee Number is 1. Then your code should look like
// Get the Employee detail whose Employee Number is 1 Employee employee = employees.Find(delegate(Employee emp) { return (emp.EmployeeNo == 1); }); Console.Write(employee.EmployeeName); Console.Write(employee.EmployeeNo);
If you want to find more than one employee based on the condition, then you can use the FIndAll method and you can implement the delegate. Then your code should look like give below.
// Get all the Employee Details whose Employee Number is greater than 1 List allEmployees = employees.FindAll(delegate(Employee emp) { return (emp.EmployeeNo > 1); }); foreach (Employee emp in allEmployees) { Console.WriteLine(emp.EmployeeName + " - " + emp.EmployeeNo); }
Feel free to post your queries here.
Regards, Brainstorming Guy aka Venkatarajan A
|
| Author: Bunty 29 Jun 2008 | Member Level: Diamond Points : 2 |
Hi, Excellent code on delegates.
Easy to understand also.
Keep posting such valuable code.
This code will be useful to everyone .
Thanks and Regards S.S.Bajoria
|