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

以下将通过一个简单的例子实现自定义类的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 }


 

转载于:https://www.cnblogs.com/arwutang/archive/2011/09/22/2184993.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值