Sort()方法是集合中默认的排序方法,它的排序方式可以通过IComparable接口实现。
如果要指定排序方式可以实现IComparer接口的Compare(T x,T y)方法Sort(Icomparer)
降序,升序年龄比较器
class AgeDesc : IComparer<Student> {
#region IComparer<Student> 成员
public int Compare(Student x, Student y)
{
return y.Age.CompareTo(x.Age);
}
#endregion
}
class AgeAsc : IComparer<Student> {
#region IComparer<Student> 成员
public int Compare(Student x, Student y)
{
return x.Age.CompareTo(y.Age);
}
#endregion
}
private void btnAgeDesc_Click(object sender, EventArgs e)
{
student.Sort(new AgeDesc());
Print(student);
}
private void Print(List<Student> stu) {
this.listView1.Items.Clear();
foreach (Student st in stu) {
ListViewItem lvi = new ListViewItem(st.Name);
lvi.SubItems.AddRange(new string[] {st.Age.ToString()});
listView1.Items.Add(lvi);
}
}
private void btnAgeAsc_Click(object sender, EventArgs e)
{
student.Sort(new AgeAsc());
Print(student);
}