[C#复习向整合]List排序

一.list自带排序方法

需要命名空间System.Collections.Generic

只能排序系统类中,继承了排序接口的类型(比如int32)

List<int> _list = new List<int>();
//乱序添加
_list.Add(1);
_list.Add(3);
_list.Add(2);
_list.Add(7);
_list.Add(4);
_list.Add(6);
_list.Add(5);

//排序
_list.Sort();
//默认升序
//ArrayList也有sort

二.自定义类排序

需要实习系统的排序接口

1.继承泛型接口

class Item : IComparable<Item>//泛型填比较类型
{
    public int money;
    public Item(int money)
    {
        this.money = money;
    }

    //排序调用时会使用的函数
    public int CompareTo(Item other)
    {
        //返回值>0,则放在比较对象后面
        //返回值<0,则放在比较对象前面
        //反过来就为降序
        if(this.money > other.money)
        {
            return 1;
        }
        else
        {
            return -1;
        }
    }
}
List<Item> itemList = new List<Item>();
itemList.Add(new Item(45));
itemList.Add(new Item(13));
itemList.Add(new Item(25));
itemList.Add(new Item(50));

itemList.Sort();
//使用list的sort方法时,会先将类型转换为接口类型,然后找到其中CompareTo方法

2.继承非泛型接口

class Item : IComparable
{
    public int money;
    public Item(int money)
    {
        this.money = money;
    }

    //排序调用时会使用的函数
    public int CompareTo(object other)
    {
        //返回值>0,则放在比较对象后面
        //返回值<0,则放在比较对象前面
        //反过来就为降序
        if(this.money > (other as Item).money)
        {
            return 1;
        }
        else
        {
            return -1;
        }
    }
}
List<Item> itemList = new List<Item>();
itemList.Add(new Item(45));
itemList.Add(new Item(13));
itemList.Add(new Item(25));
itemList.Add(new Item(50));

itemList.Sort();

三.委托函数排序

class ShopItem
{
    public int id;
    public ShopItem(int id)
    {
        this.id = id;
    }
}

List<ShopItem> shopItem = new List<ShopItem>();
shopItem.Add(new ShopItem(42));
shopItem.Add(new ShopItem(123));
shopItem.Add(new ShopItem(6));
shopItem.Add(new ShopItem(74));

//方式一,在某处声明可调用的函数
public int SortShopItem(ShopItem a, ShopItem b)
{
    //升序
    if(a.id > b.id)
        return 1;
    else
        return -1;
}
shopItem.Sort(SortShopItem);

//方式二,用lambda或匿名函数
shopItem.Sort(delegate (ShopItem a, ShopItem b)
{
    //升序
    if(a.id > b.id)
        return 1;
    else
        return -1;
});
shopItem.Sort((a, b) =>
{
    //升序
    return a.id > b.id ? 1 : -1;
});

资料来源<唐老狮C#教程>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值