简单排序我们都知道,比如冒泡排序,选择排序等待,但是只能对基本数据类型排序
但有时候我们需要对一个对象的多个条件进行排序,比如学生有学号和年龄,我们的需求是根据年龄排序,如果年龄一样再根据学号排序,这个时候是不是很打脑壳呢
也可能不是学生类排序,可能是其他任何对象的多个条件排序
我们可以使用C#中的泛型+委托的方式解决这个问题,废话不多说,上代码: 注意看注释 万能排序工具类:
class ArrayHelper { //条件委托 给a,b两个对象, 返回a基于自定义条件是否大于b public delegate bool Condition<T>(T a, T b); //冒泡排序 第二个参数使用上面的委托将自定义比较条件推迟给调用者定义 public static void Sort<T>(T[] array, Condition<T> condition) { for (int j = 0; j < array.Length - 1; j++) { for (int i = 0; i < array.Length - 1 - j; i++) { if (condition(array[i], array[i + 1])) { T temp = array[i]; array[i] = array[i + 1]; array[i + 1] = temp; } } } } }创建一个Data类和多个Data对象来测试一下效果吧!!!
测试:
class Program { //待测试数据类,将来我们会在Main函数创建多个对象来测试 class Data { public int a; public int b; public int c; public Data(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } } //测试 static void Main(string[] args) { Data data1= new Data(2, 3, 3); Data data2= new Data(2, 2, 5); Data data3= new Data(1, 3, 1); Data data4 = new Data(1, 1, 1); Data data5= new Data(1, 1, 0); Data data6= new Data(8, 1, 6); Data data7= new Data(2, 1, 6); Data[] datas= { data1, data2, data3, data4, data5, data6, data7}; //对datas数组排序,第二个委托参数是实现多条件排序的重点 ArrayHelper.Sort(datas, (a, b) => { if (a.a == b.a) { if (a.b == b.b) { return a.c > b.c; } return a.b > b.b; } return a.a > b.a; }); //输出结果 foreach (var item in datas) { Console.WriteLine(item.a + "\t" + item.b + "\t" + item.c); } } }上面的代码运行输出:
1 1 0 1 1 1 1 3 1 2 1 6 2 2 5 2 3 3 8 1 6