ampgt,一个简单的List<T>排序的例子

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 intList = new List(); 11 intList.AddRange(new[] {9, 23, 2, 1, 2, 3}); 12 Console.WriteLine("List"); 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:"); 25 List peopleList = new List 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.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 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 }

Tags: 

延伸阅读

最新评论

发表评论