C#自訂對象排序

來源:互聯網
上載者:User

標籤:

數組對象Array有一個Sort方法(點擊查看Sort方法的實現),專門是用來排序的,請看

如果我們想為自己的類添加一個排序,只需要繼承IComparable介面,實現CompareTo方法就行;

調用CompareTo方法內部實現對象的比較,通過傳回值確定對象的順序

負數值,當前對象<參數對象

正數值,當前對象>參數對象

零,兩個對象相等

下面我們就根據介面自訂自己的對象排序方式

 1     class People:IComparable 2     { 3         public uint Age { get; set; } 4  5         #region IComparable 成員 6         //實現一個人類根據年齡排序 7         public int CompareTo(object obj) 8         { 9             var people = (People)obj;10             if (this.Age > people.Age)11                 return 1;12             else if (this.Age < people.Age)13                 return -1;14             return 0;15         }16 17         #endregion18     }
 1         static void Main(string[] args) 2         { 3             var arrs =new People[] {  4                         new People{Age=15}, 5                         new People{Age=24}, 6                         new People{Age=13}, 7                         new People{Age=18}, 8                         new People{Age=14} 9                        };10           11             arrs.ToList().ForEach(a => Console.Write("{0} ", a.Age));12             Array.Sort(arrs);13             Console.WriteLine("");14             arrs.ToList().ForEach(a => Console.Write("{0} ", a.Age));15         }

 

C#自訂對象排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.