C#多条件排序OrderBy、ThenBy

发布时间:2023年12月29日

方法和效果?

?有多个排序条件,其实不用单独自己写排序方法的,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

文章来源:https://blog.csdn.net/yhx956058885/article/details/135294703
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。