C#中典型容器List.Sort()的自定义排序方法共常见有以下几个:
List<T>.Sort();
List<T>.Sort(IComparer<T> Comparer);
List<T>.Sort(int index, int count, IComparer<T> Comparer);
List<T>.Sort(Comparison<T> comparison);
下面以Student类中的三个字段Name,Score,Age三个字段为例分别实现排序方法。
(1)继承IComparable,实现CompareTo()方法。
public class Student: IComparer<Student>
{
public string Name { get; set; }
public int Age { get; set; }
public int Score { get; set; }
public int Compare([AllowNull] Student x, [AllowNull] Student y)
{
if (x.Score != y.Score)
{
return x.Score.CompareTo(y.Score);
}
else if (x.Age != y.Age)
{
return x.Age.CompareTo(y.Age);
}
else return 0;
}
}
IList<Student> list = new List<Student>
{
new Student(){Name="小明",Age=16,Score=83 },
new Student(){Name="小红",Age=15,Score=89 },
new Student(){Name="小华",Age=16,Score=83 },
new Student(){Name="小辉",Age=15,Score=88 },
new Student(){Name="小光",Age=14,Score=90 }
};
list.Sort();
(2)外部定义比较类来实现
public class MyComparer : IComparer<Student>
{
public int Compare(Student x, Student y)
{
if (x.Score != y.Score)
{
return x.Score.CompareTo(y.Score);
}
else if (x.Age != y.Age)
{
return x.Age.CompareTo(y.Age);
}
else return 0;
}
}
IList<Student> list = new List<Student>
{
new Student(){Name="小明",Age=16,Score=83 },
new Student(){Name="小红",Age=15,Score=89 },
new Student(){Name="小华",Age=16,Score=83 },
new Student(){Name="小辉",Age=15,Score=88 },
new Student(){Name="小光",Age=14,Score=90 }
};
list.Sort(new MyComparer());
(3)直接使用委托实现
先定义一个比较委托
public delegate int CompareDelegate<in T>(T x, T y);
public static int ComparerMethod(Student x, Student y)
{
if (x.Score != y.Score)
{
return x.Score.CompareTo(y.Score);
}
else if (x.Age != y.Age)
{
return x.Age.CompareTo(y.Age);
}
else return 0;
}
IList<Student> list = new List<Student>
{
new Student(){Name="小明",Age=16,Score=83 },
new Student(){Name="小红",Age=15,Score=89 },
new Student(){Name="小华",Age=16,Score=83 },
new Student(){Name="小辉",Age=15,Score=88 },
new Student(){Name="小光",Age=14,Score=90 }
};
CompareDelegate<Student> comparison = ComparerMethod;
list.Sort(comparison);
推荐文章: