c#Lsit排序

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;
    }
}
相关推荐
fqbqrr5 小时前
2606C++,C++构的多态
开发语言·c++
biter down6 小时前
从 0 到 1 搭建 Python 接口自动化测试框架(博客系统实战)
开发语言·python
threelab7 小时前
Three.js 物理模拟着色器 | 三维可视化 / AI 提示词
开发语言·前端·javascript·人工智能·3d·着色器
武器大师727 小时前
lv_binding_js 代码解读
开发语言·javascript·ecmascript
不知名的老吴7 小时前
线程的生命周期之线程“插队“
java·开发语言·python
kaikaile19958 小时前
数字全息图处理系统(C# 实现)
开发语言·c#
秋99 小时前
Go语言(Golang)开发工程师全景解析:岗位职责·语言优势与使用场景·各城市薪资·发展前景·高考志愿填报(2026版)
开发语言·golang·高考
huangdong_10 小时前
1688商品图片采集技术解析:登录态处理与SKU图自动分类
开发语言
chase_my_dream10 小时前
C++ + SLAM 高频面试问题整理
开发语言·c++·面试