An in depth analysis of the classic delegate ordering of

  • 2020-05-17 06:11:51
  • OfStack

We're used to numerical sorting, but sometimes we want our Sort() method to sort any object, such as a piece of client code that contains an Currency array or some other class or structure. Here we use the delegate and encapsulate this method for comparison.

We're still going to use the classic bubble sort for sorting, but if you have a lot of data you can switch to your own more efficient sorting algorithm.

The whole code is given first:


public class BubbleSorter
{
 public static void Sort(object[] sortArray, CompareOperation gtMethod)
 {
  for (int i = 0; i < sortArray.Length; i++)
  {
   for (int j = 0; j < sortArray.Length; j++)
   {
    if (gtMethod(sortArray[j], sortArray[i]))
    {
     object tmp = sortArray[i];
     sortArray[i] = sortArray[j];
     sortArray[j] = tmp;
    }
   }
  }
 }
}
public class Employee
{
 private string name;
 private decimal salary;
 public Employee(string name, decimal salary)
 {
  this.name = name;
  this.salary = salary;
 }
 public override string ToString()
 {
  return string.Format(name.PadRight(20) + "{0:C}", salary);
 }
 public static bool RSalaryIsGreater(object lObj, object rObj)
 {
  Employee lEmployee = lObj as Employee;
  Employee rEmployee = rObj as Employee;
  return rEmployee.salary > lEmployee.salary;
 }
}

One more call example:

public delegate bool CompareOperation(object lObj, object rObj);
class Program
{
 static void Main(string[] args)
 {
  Employee[] employees = 
  {
   new Employee("Tommy",20000),
   new Employee("Elmer",10000),
   new Employee("Daffy", 25000),
   new Employee("Wiley",1000000),
   new Employee("Foghorn",23000),
   new Employee("RoadRunner",50000),
  };
  CompareOperation employeeCompareOperation = new CompareOperation(Employee.RSalaryIsGreater);
  BubbleSorter.Sort(employees, employeeCompareOperation);
  for (int i = 0; i < employees.Length; i++)
  {
   Console.WriteLine(employees[i].ToString());
  }
 }
}


Related articles: