list的自带排序方法
List.Sort()只能对系统自带变量进行排序
Sort(IComparer<T> comparer)
是要实现IComparer的继承及接口CompareTo方法的实现
class Item : IComparable<Item>
{
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(Comparison<T> comparison)
传入一个符合 Comparison<T> 委托的方法/匿名函数/Lambda
class ShopItem
{
public int id;
public ShopItem(int id)
{
this.id = id;
}
}
List<ShopItem> shopItems = new List<ShopItem>();
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;
}
}