List的排序方法

这篇博客介绍了C#中List的两种数值类型和对象类型数据的排序方法。对于数值类型,使用了List的Sort()方法进行排序;对于对象类型,通过Peopel类的age属性,利用LINQ表达式和List的Sort()方法实现了从小到大和从大到小的排序。示例代码详细展示了各种排序实现。
摘要由CSDN通过智能技术生成

List的排序方法

1.对于数值类型的排序
   public List<int> TestList=new List<int>();
    void Start()
    {
        TestList.Add(9);
        TestList.Add(7);
        TestList.Add(2);
        TestList.Add(12);
        TestList.Add(1);
        TestList.Sort();//从小到大
        foreach (var item in TestList)
        {
            Debug.Log(item);
        }
    }

运行结果:
在这里插入图片描述

2.根据对象里的数据对list排序
public class Peopel
{
    public string name;
    public int age;
}
  public List<Peopel> pe = new List<Peopel>();
    void Start()
    {
        Peopel p1 = new Peopel()
        {
            name = "q",
            age = 2
        };
        Peopel p2 = new Peopel()
        {
            name = "w",
            age = 5
        };
        Peopel p3 = new Peopel()
        {
            name = "e",
            age = 1
        };
        Peopel p4 = new Peopel()
        {
            name = "r",
            age = 35
        };
        Peopel p5 = new Peopel()
        {
            name = "t",
            age = 0
        };
        pe.Add(p1);
        pe.Add(p2);
        pe.Add(p3);
        pe.Add(p4);
        pe.Add(p5);
        Paixu();
        foreach (var item in pe)
        {
            Debug.Log(item.age);
        }
    }
    //排序方法
    void Paixu()
    {
        //排序的方法
        //1.通过linq表达式 从小到大
        pe.OrderBy(_ => _.age).ToList();
        //2.通过linq表达式 从大到小
        pe.OrderByDescending(_ => _.age).ToList();
        //3.通过list自带的函数 从小到大
        pe.Sort((pe, pe2) => pe.age.CompareTo(pe2.age));
        //4.通过list自带的函数 从大到小
        pe.Sort((pe, pe2) => pe2.age.CompareTo(pe.age));
    }

运行结果(此图为从小到大的排序图):
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值