C# List Sort的三種方法
阿新 • • 發佈:2019-02-09
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { List<Person> list = new List<Person>(); list.Add(new Person("AA", 50)); list.Add(new Person("BB", 20)); list.Add(new Person("CC", 30)); list.Add(new Person("DD", 70)); Comparison<Person> comparison = new Comparison<Person> ((Person x, Person y) => { if (x.Old < y.Old) return -1; else if (x.Old == y.Old) return 0; else return 1; }); list.Sort(comparison);//1、Comparison<Person> list.Sort(new Person().Compare);//2、IComparer<Person> list.Sort();//3、IComparable Console.ReadKey(); } } class Person : IComparable, IComparer<Person> { string name; public Person() { } public Person(string name, int old) { this.name = name; this.old = old; } public string Name { get { return name; } set { name = value; } } int old; public int Old { get { return old; } set { old = value; } } public int CompareTo(Object o) { if (this.old > ((Person)o).old) return 1; else if (this.old == ((Person)o).old) return 0; else return -1; } public int Compare(Person x, Person y) { if (x.old < y.old) return -1; else if (x.old == y.old) return 0; else return 1; } }