C# 泛型集合快速排序类:支持按属性名灵活排序

咖啡半糖
咖啡半糖
发布时间:2026-10-14 | 2人浏览过
原创

在 C# 开发中,针对包含多个字段的数据集合进行排序通常需要根据特定字段调整比较逻辑。本代码展示了一个通用的 ListSorter 类,它结合了泛型约束与反射技术,能够根据指定的属性名称自动识别排序依据,并对 IList<T> 类型的集合执行快速排序算法,同时支持升序与降序方向控制。

核心功能与实现原理

该排序类的主要优势在于其通用性。传统的排序方法往往需要为每个实体类编写单独的比较器(IComparer),而此方案通过以下两点实现了“一次编写,多处复用”:

  1. 参数化集合类型:使用泛型 TCollection 和 TItem 限制输入必须为列表集合及其中元素类型,确保类型安全。
  2. 反射定位属性:利用 Type.GetProperties() 遍历目标对象的属性,通过名称匹配找到需要参与排序的具体字段。

重要前提:参与排序的属性类型必须实现了 IComparable 接口。在 .NET 标准库中,int、string、DateTime 等基础类型已默认实现该接口,可直接用于排序。

第1步:准备排序数据与环境

在使用该类之前,请确保你的项目引用了 System.Reflection 命名空间,因为排序逻辑依赖于反射获取属性信息。假设你有一个用户实体列表:

class User
{
    public string Name { get; set; }
    public int Age { get; set; }
}

// 初始化数据
var users = new List<User>
{
    new User { Name = "Charlie", Age = 30 },
    new User { Name = "Alice", Age = 25 },
    new User { Name = "Bob", Age = 35 }
};

第2步:调用 SortList 进行排序

ListSorter.SortList<> 方法是入口点。它接受三个关键参数:

  • ref list:需要被排序的集合引用,因为是原地排序,需使用 ref 关键字。
  • property:字符串形式的属性名称(如 "Name" 或 "Age")。
  • direction:SortDirection.Enumerable 枚举值,可选 Ascending(升序)或 Descending(降序)。
// 示例:按 Name 属性升序排序
ListSorter.SortList<List<User>, User>(ref users, "Name", SortDirection.Ascending);

// 示例:按 Age 属性降序排序
ListSorter.SortList<List<User>, User>(ref users, "Age", SortDirection.Descending);

完整源代码

以下是完整的 ListSorter 类及相关枚举定义。代码使用了经典的双指针快速排序算法(QuickSort):

复制代码 代码如下:
/// <summary>
/// 对集合进行排序,如
/// List<User> users=new List<User>(){.......}
/// ListSorter.SortList<list<User>,User>(ref users,"Name",SortDirection.Ascending);
/// </summary>
public class ListSorter
{
    /// <summary>
    /// 公共入口:根据指定属性名称和方向对集合进行排序
    /// </summary>
    public static void SortList<TCollection, TItem>(ref TCollection list, string property, SortDirection direction)
        where TCollection : IList<TItem>
    {
        PropertyInfo[] propertyinfos = typeof(TItem).GetProperties();
        foreach (PropertyInfo propertyinfo in propertyinfos)
        {
            if (propertyinfo.Name == property) // 取得指定的排序属性
            {
                QuickSort<TCollection, TItem>(ref list, 0, list.Count - 1, propertyinfo, direction);
            }
        }
    }

    /// <summary>
    /// 快速排序算法核心实现
    /// </summary>
    /// <typeparam name="TCollection">集合类型,需要实现Ilist<T>集合</typeparam>
    /// <typeparam name="TItem">集合中对象的类型</typeparam>
    /// <param name="list">集合对象</param>
    /// <param name="left">起始位置,从0开始</param>
    /// <param name="right">终止位置</param>
    /// <param name="propertyinfo">集合中对象的属性,属性必须要实现IComparable接口</param>
    /// <param name="direction">排序类型(升序或降序)</param>
    private static void QuickSort<TCollection, TItem>(ref TCollection list, int left, int right,
        PropertyInfo propertyinfo, SortDirection direction)
        where TCollection : IList<TItem>
    {
        if (left < right)
        {
            int i = left, j = right;
            TItem key = list[left];

            while (i < j)
            {
                if (direction == SortDirection.Ascending)
                {
                    // 升序:右侧扫描寻找小于基准值的元素
                    while (i < j && ((IComparable)propertyinfo.GetValue(key, null)).CompareTo((IComparable)propertyinfo.GetValue(list[j], null)) < 0)
                    {
                        j--;
                    }
                    if (i < j)
                    {
                        list[i] = list[j];
                        i++;
                    }

                    // 左侧扫描寻找大于基准值的元素
                    while (i < j && ((IComparable)propertyinfo.GetValue(key, null)).CompareTo((IComparable)propertyinfo.GetValue(list[i], null)) > 0)
                    {
                        i++;
                    }
                    if (i < j)
                    {
                        list[j] = list[i];
                        j--;
                    }
                    list[i] = key;
                }
                else
                {
                    // 降序:逻辑相反
                    while (i < j && ((IComparable)propertyinfo.GetValue(key, null)).CompareTo((IComparable)propertyinfo.GetValue(list[j], null)) > 0)
                    {
                        j--;
                    }
                    if (i < j)
                    {
                        list[i] = list[j];
                        i++;
                    }

                    while (i < j && ((IComparable)propertyinfo.GetValue(key, null)).CompareTo((IComparable)propertyinfo.GetValue(list[i], null)) < 0)
                    {
                        i++;
                    }
                    if (i < j)
                    {
                        list[j] = list[i];
                        j--;
                    }
                    list[i] = key;
                }
            }

            // 执行递归调用
            QuickSort<TCollection, TItem>(ref list, left, i - 1, propertyinfo, direction);
            QuickSort<TCollection, TItem>(ref list, i + 1, right, propertyinfo, direction);
        }
    }
}

/// <summary>
/// 排序类型枚举
/// </summary>
public enum SortDirection
{
    Ascending,
    Descending
}

注意事项与排错

  • 属性不存在:如果传入的 property 名称在 TItem 中找不到匹配的公有属性,循环将结束且不执行任何操作,不会抛出异常,但集合不会被排序。建议在实际应用中增加日志记录以方便调试。
  • 类型兼容性:如果尝试对未实现 IComparable 的自定义复杂对象属性进行排序,(IComparable)... 强转将在运行时抛出 InvalidCastException。
  • 性能考量:由于排序过程中频繁使用反射获取属性值(GetValue),对于百万级以上的海量数据排序,性能可能不如手写专用比较器或使用编译表达式树优化后的方案。但对于常规业务数据量,此方案简洁且高效。

以上就是 C# 集合快速排序类实现支持的详细内容,更多关于 C# 泛型编程与算法优化的资料请关注本站其它相关文章!

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表