定义端:
工具类:
/// <summary>
/// 用于比较排序的数据的委托
/// </summary>
/// <typeparam name="T">传入的对象(数据类型)</typeparam>
/// <typeparam name="TKey">要比较排序的数据,即对象的属性 或对象本身</typeparam>
/// <param name="tObj">传入的对象(数据类型)</param>
/// <returns></returns>
public delegate TKey SelectHandler<T, TKey>(T tObj);
//数组帮助类
public static class ArrayHelper
{
/// <summary>
/// 对泛型(任意类型)数组进行升序排序(对于 自己创建的数据类型 可根据自定义属性排序)
/// </summary>
/// <typeparam name="T">传入的对象(数据类型)</typeparam>
/// <typeparam name="TKey">对象的属性 或对象本身</typeparam>
/// <param name="array">传入的对象(数据类型)数组 要比较排序的数据</param>
/// <param name="handler">选择比较排序的数据的委托(方法) 用于比较的数据</param>
/// <returns>排序后的数组 数据</returns>
public static T[] ArraySort<T, TKey>(T[] array, SelectHandler<T, TKey> handler)
where TKey : IComparable<TKey>
{
//冒泡排序 连续两两比较
for (int r = 0; r < array.Length - 1; r++)//n-1 轮比较
{
for (int c = 0; c < array.Length - 1 - r; c++)//每轮比较的次数
{
//handler(array[c]) 委托调用 返回值为TKey 要比较的数据
if (handler(array[c]).CompareTo(handler(array[c + 1])) > 0)
{
T temp = array[c];
array[c] = array[c + 1];
array[c + 1] = temp;
}
}
}
return array;
}
}
自定义数据类型(学生类):
//学生类
class Student
{
public int Id { set; get; }
public string Name { set; get; }
public int Age { set; get; }
/// <summary>
/// 自定义头类型
/// </summary>
public Head head;
}
/// <summary>
/// 头类 默认比较Count
/// </summary>
class Head:IComparable<Head>
{
public int Count { set; get; }
/// <summary>
/// 该类中比较器 默认比较 Count
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public int CompareTo(Head other)
{
return this.Count.CompareTo(other.Count);
}
}
调用端:
static void Main(string[] args)
{
Student[] student = new Student[]
{
new Student(){ Id=1,Age=18,Name="D",head =new Head{ Count = 5} },
new Student(){ Id=2,Age=17,Name="T",head =new Head{ Count = 3}},
new Student(){ Id=3,Age=16,Name="C",head =new Head{ Count = 6}}
};
int[] num = { 1, 5, 3, 6, 2 };
//对整型数组排序
ArrayHelper.ArraySort(num,(a)=>a);//num:1 2 3 5 6
//根据学生类的年龄排序
//ArrayHelper.ArraySort(student,(a)=> { return a.Age; });//student.Age:16 17 18
//根据学生类的头数据排序
ArrayHelper.ArraySort(student,(a)=> { return a.head; });//student.head:3 5 6
}