以下将通过一个简单的例子实现自定义类的List的排序
1 using System;
2 using System.Collections.Generic;
3
4 namespace ListSort
5 {
6 class Program
7 {
8 static void Main(string[] args)
9 {
10 List<int> intList = new List<int>();
11 intList.AddRange(new[] {9, 23, 2, 1, 2, 3});
12 Console.WriteLine("List<int>");
13 foreach (int i in intList)
14 {
15 Console.Write(i.ToString()+" ");
16 }
17 Console.WriteLine("\nUse List.sort");
18 intList.Sort();
19 foreach (int i in intList)
20 {
21 Console.Write(i.ToString() + " ");
22 }
23
24 Console.WriteLine("\n\nList<People>:");
25 List<People> peopleList = new List<People>
26 {
27 new People() {Name = "people1", Age = 23},
28 new People() {Name = "people2", Age = 21},
29 new People() {Name = "people3", Age = 33},
30 new People() {Name = "people4", Age = 20},
31 new People() {Name = "people4", Age = 22}
32 };
33
34 foreach (People people in peopleList)
35 {
36 Console.WriteLine(people.ToString());
37 }
38 Console.WriteLine("\nUse List<People>.Sort:");
39 peopleList.Sort(new PeopleSort());
40 foreach (People people in peopleList)
41 {
42 Console.WriteLine(people.ToString());
43 }
44 Console.Read();
45 }
46
47 public class People
48 {
49 public string Name { get; set; }
50 public int Age { get; set; }
51
52 public override string ToString()
53 {
54 return Name + " Age = " + Age;
55 }
56 }
57
58 public class PeopleSort : IComparer<People>
59 {
60 public int Compare(People x,People y)
61 {
62 if (x.Age > y.Age) return 1;
63 if (x.Age < y.Age) return -1;
64 return 0;
65 }
66 }
67 }
68 }