C# 使用IComparer自訂List類的排序方案

來源:互聯網
上載者:User

標籤: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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.