We are familiar with numeric sorting, but sometimes we want our Sort () method to Sort any object, for example, if a client code contains an array of Currency structures or other classes and structures, sort the array. Here we use the delegate and encapsulate this method for comparison.
We still use the classic Bubble sorting. If the data size is large, you can replace it with your own more efficient sorting algorithm.
The entire code is provided first:
Copy codeThe Code is as follows: 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;
}
}
Let's give another call example:Copy codeThe Code is as follows: 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 ());
}
}
}