C # sorting custom objects,

Source: Internet
Author: User

C # sorting custom objects,

The Array object Array has an Sort method (click to view the implementation of the Sort method), which is specially used for sorting. Please refer

If we want to add a sort for our class, we only need to inherit the IComparable interface and implement the CompareTo method;

Call the CompareTo method to internally implement object comparison, and determine the object order through the return value

Negative value, current object <parameter object

Positive Value, current Object> parameter object

Zero. Two objects are equal.

Next, we will customize the object sorting method based on the interface.

1 class People: IComparable 2 {3 public uint Age {get; set;} 4 5 # region IComparable member 6 // implement a human sort by Age 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         }

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.