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();
}
参数说明
List<T> items
: 要排序的对象列表,其中T
是对象的类型。List<TKey> order
: 定义排序顺序的列表,其中TKey
是排序键的类型。Func<T, TKey> keySelector
: 一个函数,用于从每个对象中提取用于排序的键。
逻辑步骤
创建排序顺序字典:
- 通过
Select
方法和ToDictionary
方法,将order
列表转换为一个字典orderIndex
,字典的键是排序值,值是它们的索引。这样可以快速查找每个排序键的优先级。
- 通过
排序:
- 使用 LINQ 的
OrderBy
方法,根据orderIndex
字典中的索引对items
进行排序。如果某个键不在字典中,则返回int.MaxValue
,确保这些项在排序结果中排到最后。
- 使用 LINQ 的
使用案例:
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();
}
}