List sort () sorts custom objects

Source: Internet
Author: User

Custom Object User, which sorts the List <User> set by age. [Csharp] public class User {public User (int age, string name) {Age = age; Name = name;} public int Age {get; set ;} public string Name {get; set ;}} here we need a custom comparator [csharp] public static int CompareByAge (User x, User y) // from large to small sorters {if (x = null) {if (y = null) {return 0 ;}return 1 ;}if (y = null) {return-1;} int retval = y. age. compareTo (x. age); return retval;} then you can use List <T>. sort (CompareByAge) to sort [csharp] List <User> list = new List <User> {new User (14, "aa"), new User (17, "bb"), new User (12, "cc"), new User (33, "dd")}; www.2cto.com foreach (var item in list) {Console. writeLine (item. name + ":" + item. age);} Console. writeLine ("sorted"); list. sort (CompareByAge); foreach (var item in list) {Console. writeLine (item. name + ":" + item. age);} Console. readKey ();

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.