標籤:style http 使用 os for 2014 ar 代碼
List類中不帶參數的Sort函數可以用來為List類中的元素排序,但如果List類中的元素類型本身不能直接進行比較(如自訂的struct和很多class),或是希望採用更加靈活的自訂比較方式,可以通過繼承了IComparer介面的函數來解決。
程式碼範例如下:
1)聲明一個類
/// <summary>/// 人物類/// </summary>public class Person{ public string Name; public int Age; public override string ToString() { return "Name: " + Name + " Age: " + Age; }}
2)聲明一個繼承了介面IComparer的類
/// <summary>/// 比較人物類執行個體大小,實現介面IComparer/// </summary>public class PersonComparer : IComparer<Person>{ public int Compare(Person x, Person y) { if (x == null && y == null) return 0; if (x == null) return -1; if (y == null) return 1; //TODO:Person類執行個體X與Y的比較規則 //按姓名由小到大排列,姓名相同的人年齡大的在前 { int temp = string.Compare(x.Name, y.Name); if (temp > 0) return -1; else if (temp < 0) return 1; if (x.Age > y.Age) return 1; if (x.Age < y.Age) return -1; } return 0; }}
3)Main函數,建立一個List,並使用剛建立的PersonComparer類中的規則對List進行排序
static void Main(string[] args){ List<Person> a = new List<Person>(); a.Add(new Person() { Name = "Tsybius", Age = 23 }); a.Add(new Person() { Name = "Galatea", Age = 21 }); a.Add(new Person() { Name = "Lucius", Age = 22 }); a.Add(new Person() { Name = "Septimus", Age = 22 }); a.Add(new Person() { Name = "Octavius", Age = 22 }); a.Add(new Person() { Name = "Lucius", Age = 24 }); //輸出a中全部元素 Console.WriteLine("排序前"); foreach (var v in a) { Console.WriteLine(v.ToString()); } Console.WriteLine("-"); //對a進行排序 a.Sort(new PersonComparer()); //輸出a中全部元素 Console.WriteLine("排序後"); foreach (var v in a) { Console.WriteLine(v.ToString()); } Console.WriteLine("-"); Console.ReadLine();}
4)程式運行樣本
END