对于数值型的排序我们都已经司空见惯了,但我们有时候希望我们的Sort()方法能够给任何对象排序,比如某段客户机代码包含Currency结构数组或其他的类和结构,就需要对该数组排序。这里我们使用委托并封装这个方法进行比较。
排序我们还是使用经典的冒泡排序,如果数据量较大你可以换为你自己的更高效的排序算法。
先给出整个代码:
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; } }
再给一个调用示例:
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()); } } }