SortByCustomOrder 根据指定的顺序对任意类型的列表进行排序

发布于:2025-07-12 ⋅ 阅读:(19) ⋅ 点赞:(0)

static List<T> SortByCustomOrder<T, TKey>(
    List<T> items,
    List<TKey> order,
    Func<T, TKey> keySelector)
{
    // 将排序顺序转换为字典
    var orderIndex = order
        .Select((x, index) => new { Value = x, Index = index })
        .ToDictionary(x => x.Value, x => x.Index);

    // 使用字典进行排序
    return items
        .OrderBy(item => orderIndex.TryGetValue(keySelector(item), out int index) ? index : int.MaxValue)
        .ToList();
}

参数说明
  1. List<T> items: 要排序的对象列表,其中 T 是对象的类型。
  2. List<TKey> order: 定义排序顺序的列表,其中 TKey 是排序键的类型。
  3. Func<T, TKey> keySelector: 一个函数,用于从每个对象中提取用于排序的键。
逻辑步骤
  1. 创建排序顺序字典:

    • 通过 Select 方法和 ToDictionary 方法,将 order 列表转换为一个字典 orderIndex,字典的键是排序值,值是它们的索引。这样可以快速查找每个排序键的优先级。
  2. 排序:

    • 使用 LINQ 的 OrderBy 方法,根据 orderIndex 字典中的索引对 items 进行排序。如果某个键不在字典中,则返回 int.MaxValue,确保这些项在排序结果中排到最后。

使用案例:

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

public class ProductData
{
    public string DepartmentId { get; set; }
}

public class ParkMill
{
    public List<string> DepartmentCode { get; set; }
}

public class Request
{
    public ParkMill parkMill { get; set; }
}

class Program
{
    static void Main()
    {
        var request = new Request
        {
            parkMill = new ParkMill
            {
                DepartmentCode = new List<string> { "B", "A", "C", "D" }
            }
        };

        var productDatas = new List<ProductData>
        {
            new ProductData { DepartmentId = "C" },
            new ProductData { DepartmentId = "A" },
            new ProductData { DepartmentId = "D" },
            new ProductData { DepartmentId = "B" },
            new ProductData { DepartmentId = "E" } // E 不在 DepartmentCode 中
        };

        // 调用通用的排序方法
        var sortedProductDatas = SortByCustomOrder(productDatas, request.parkMill.DepartmentCode, p => p.DepartmentId);

        foreach (var product in sortedProductDatas)
        {
            Console.WriteLine(product.DepartmentId);
        }
    }

    // 通用排序方法
    static List<T> SortByCustomOrder<T, TKey>(
        List<T> items,
        List<TKey> order,
        Func<T, TKey> keySelector)
    {
        // 将排序顺序转换为字典
        var orderIndex = order
            .Select((x, index) => new { Value = x, Index = index })
            .ToDictionary(x => x.Value, x => x.Index);

        // 使用字典进行排序
        return items
            .OrderBy(item => orderIndex.TryGetValue(keySelector(item), out int index) ? index : int.MaxValue)
            .ToList();
    }
}


网站公告

今日签到

点亮在社区的每一天
去签到