|
我們可以對集合中的字符串類型的數(shù)據(jù)排序。
List<string> ary = new List<string>(); ary.Add("a"); ary.Add("你好"); ary.Add("c"); ary.Sort(); foreach (string str in ary) { Console.WriteLine(str); }
但我們不能對兩個(gè)對象進(jìn)行排序。如
List<Student> student = new List<Student>(); Student stu1 = new Student("dd", 19); Student stu2 = new Student("你好", 13); Student stu3 = new Student("你", 13); student.Add(stu1); student.Add(stu2); student.Add(stu3); student.Sort(); foreach(Student stu in student){ Console.WriteLine(stu.Name+stu.Age); } 這樣程序會拋出異常,必須至少有一個(gè)對象實(shí)現(xiàn)IComparable
這個(gè)IComparable是一個(gè)接口里面有個(gè)一個(gè)沒有實(shí)現(xiàn)的方法
int CompareTo(Object obj)
如果實(shí)現(xiàn)此方法,就可以比較兩個(gè)對象了。
1年齡比較
public int CompareTo(Student other) { //if (!(other is Student)) { // throw new Exception("student"); //} return this.Age.CompareTo(other.Age); }
2如果不是泛型,需要判斷兩個(gè)對象是否能夠比較和轉(zhuǎn)換對象
public int CompareTo(object obj) {
//判斷類型 if (!(obj is Teacher)) { throw new Exception("不能比較"); } else {
//轉(zhuǎn)換類型 Teacher s = obj as Teacher; return this.YearOfwork.CompareTo(s.YearOfwork); } }
Sort()方法是集合中默認(rèn)的排序方法,它的排序方式可以通過IComparable接口實(shí)現(xiàn)。
如果要指定排序方式可以實(shí)現(xiàn)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); }
|