C#多条件排序OrderBy、ThenBy

方法和效果 

 有多个排序条件,其实不用单独自己写排序方法的,C#内置了排序方法:

引用命名空间System.Linq

正向排序的方法:OrderBy首要条件;ThenBy次要条件,可以连续多个使用
同理,逆向排序对应的方法是OrderByDescending、ThenByDescending
正向排序和逆向排序可以交叉使用

完整代码

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class Test01 : MonoBehaviour
{
    public class student
    {
        public int id { get; set; }
        public string name { get; set; }
        public string hometown { get; set; }

        public student(int id, string name, string hometown)
        {
            this.id = id;
            this.name = name;
            this.hometown = hometown;
        }

        public override string ToString()
        {
            return $"{this.id}  {this.name}  {this.hometown}";
        }
    }

    // Start is called before the first frame update
    List<student> list = new List<student>()
    {
        new student(1, "1", "3"),
        new student(1, "1", "2"),
        new student(1, "2", "1"),
        new student(2, "2", "2"),
        new student(3, "2", "1"),
        new student(2, "3", "1"),
        new student(1, "3", "3"),
    };

    void PrintList()
    {
        foreach (var VARIABLE in list)
        {
            Debug.Log(VARIABLE.ToString());
        }

        Debug.LogWarning("--------------------------");
    }

    void Start()
    {
        PrintList();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.A))
        {
            //依次安装id,name,hometown正向排序
            list = list.OrderBy(x => x.id).ThenBy(x => x.name).ThenBy(x => x.hometown).ToList();
            ;
            PrintList();
        }

        if (Input.GetKeyDown(KeyCode.S))
        {
            //依次安装id,name,hometown反向排序
            list = list.OrderByDescending(x => x.id).ThenByDescending(x => x.name).ThenByDescending(x => x.hometown).ToList();
            ;
            PrintList();
        }
    }
}

参考连接

 Queryable.ThenBy Method (System.Linq) | Microsoft Learn

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-30 23:04:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-30 23:04:02       101 阅读
  3. 在Django里面运行非项目文件

    2023-12-30 23:04:02       82 阅读
  4. Python语言-面向对象

    2023-12-30 23:04:02       91 阅读

热门阅读

  1. Linux的capability深入分析

    2023-12-30 23:04:02       56 阅读
  2. shell编程进阶

    2023-12-30 23:04:02       66 阅读
  3. 纯前端 文件上传汇总

    2023-12-30 23:04:02       51 阅读
  4. 西安电子科技大学现代密码学实验四报告

    2023-12-30 23:04:02       39 阅读
  5. 2023.12.28 Python 多进程多线程

    2023-12-30 23:04:02       44 阅读
  6. VSCode的介绍和入门

    2023-12-30 23:04:02       54 阅读
  7. 强化学习计划

    2023-12-30 23:04:02       58 阅读
  8. Git三种方法从远程仓库拉取指定分支

    2023-12-30 23:04:02       57 阅读
  9. 2分钟快速了解Nginx

    2023-12-30 23:04:02       57 阅读
  10. LeetCode 155:最小栈

    2023-12-30 23:04:02       55 阅读
  11. 总结心得:各设计模式使用场景

    2023-12-30 23:04:02       56 阅读