List 排序
一、List 自带的排序
1 2 3 4 5
| List<int> list = new List<int>();
list.Sort();
list.Reverse();
|
二、自定义类的排序
1.实现方法
继承 IComparable 或者 IComparable<>接口 并实现对应 CompareTo 方法
2.示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Item:IComparable<Item> { public int money; pulic Item(int money) { this.money = money; } public int CompareTo(Item other) { if(this.money > other.money) return 1; else return -1;
} }
List<Item> list = new List<Item>(); list.Sort();
|
三、通过委托函数进行委托函数
1.实现方法
Sort 函数中可以传入函数委托
2.示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| class Item { public int money; pulic Item(int money) { this.money = money; } }
static int SortItem(Item a,Item b) { if(a.money>b.money) return 1; else return -1; }
List<Item> list = new List<Item>(); list.Sort(SortItem);
|