Comparison
delegate is used to sort or order the data inside a collection. It takes two parameters as generic input type and return type should always be int
. This is how we can declare Comparison
delegate.Code:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace genericUserDefined
- {
- public class Employee : IComparable<Employee>
- {
- public int eid { get; set; }
- public string first_name { get; set; }
- public string last_name { get; set; }
- public string department { get; set; }
- public double salary { get; set; }
- public int CompareTo(Employee other)
- {
- if (this.eid > other.eid)
- return 1;
- else if (this.eid < other.eid)
- return -1;
- else
- return 0;
- }
- }
- public class compareEmployee : IComparer<Employee>
- {
- public int Compare(Employee x, Employee y)
- {
- if (x.salary > y.salary)
- return 1;
- else if (x.salary < y.salary)
- return -1;
- else
- return 0;
- }
- }
- }
- //Main class
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace genericUserDefined
- {
- class Program
- {
- public static int compareNames(Employee n1, Employee n2)
- {
- return n1.first_name.CompareTo(n2.first_name);
- }
- static void Main(string[] args)
- {
- List<Employee> elist = new List<Employee>();
- Employee e1 = new Employee();
- e1.eid = 101;
- e1.first_name = "Sujan";
- e1.last_name = "Hasan";
- e1.department = "IT";
- e1.salary = 55000.00;
- elist.Add(e1);
- Employee e2 = new Employee();
- e2.eid = 102;
- e2.first_name = "Shakil";
- e2.last_name = "Sorker";
- e2.department = "Networking";
- e2.salary = 175000.00;
- elist.Add(e2);
- Employee e3 = new Employee();
- e3.eid = 100;
- e3.first_name = "Shimul";
- e3.last_name = "Hossain";
- e3.department = "Marketing";
- e3.salary = 75000.50;
- elist.Add(e3);
- print(elist);
- Console.WriteLine("\nAfter sorting the value with respect of employee id:\n");
- elist.Sort();
- print(elist);
- Console.WriteLine("\nSorting with respect to salary:\n");
- compareEmployee obj = new compareEmployee();
- elist.Sort(obj);
- print(elist);
- Comparison<Employee>obj1=new Comparison<Employee>(compareNames);//Using comparison delegate
- Console.WriteLine("\nSorting with respect to first_name:\n");
- elist.Sort(obj1);
- print(elist);
- Console.ReadKey();
- }
- public static void print(List<Employee> emp)
- {
- foreach (Employee obj in emp)
- {
- Console.WriteLine(obj.eid+" "+obj.first_name+" "+obj.last_name+" "+obj.department+" "+obj.salary);
- }
- }
- }
- }
0 Comments:
Post a Comment