c#Lsit排序
list的自带排序方法List.Sort()只能对系统自带变量进行排序Sort(IComparerT comparer)是要实现IComparer的继承及接口CompareTo方法的实现class Item : IComparableItem { public int money; public Item(int money) { this.money money; } public int CompareTo(Item other) { if( this.money other.money ) { return -1; } else { return 1; } } }返回值的含义小于0放在传入对象的前面等于0:保持当前的位置不变大于0放在传入对象的后面可以简单理解 传入对象的位置 就是0如果你的返回为负数 就放在它的左边 也就前面如果你返回正数 就放在它的右边 也就是后面Sort(ComparisonT comparison)传入一个符合ComparisonT委托的方法/匿名函数/Lambdaclass ShopItem { public int id; public ShopItem(int id) { this.id id; } } ListShopItem shopItems new ListShopItem(); shopItems.Add(new ShopItem(2)); shopItems.Add(new ShopItem(1)); shopItems.Add(new ShopItem(4)); shopItems.Sort(delegate (ShopItem a, ShopItem b) { if (a.id b.id) { return -1; } else { return 1; } }); shopItems.Sort((a, b) { return a.id b.id ? 1 : -1;}); shopItems.Sort(SortShopItem); static int SortShopItem( ShopItem a, ShopItem b ) { if (a.id b.id) { return -1; } else { return 1; } }