You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中自定义PropertyInfo数组的排序规则?

按指定类型优先级排序PropertyInfo集合

你可以通过利用类型优先级列表的索引位置作为排序依据,结合LINQ的OrderBy方法实现动态排序。核心逻辑是:让每个属性的类型在优先级列表中的索引决定它的排序位置,不在列表中的属性可以统一排在末尾(或你指定的位置)。

完整实现代码

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

// 定义示例中的File类(假设你已有该类,这里仅作示意)
public class File { }

public class Test
{
    public int Number { get; set; }
    public string Text { get; set; }
    public bool IsActive { get; set; }
    public File File { get; set; }
}

class Program
{
    static void Main()
    {
        // 1. 获取Test类的所有PropertyInfo
        PropertyInfo[] properties = typeof(Test).GetProperties();

        // 2. 定义动态可修改的类型优先级列表(可根据需求随时调整)
        List<Type> typePriority = new List<Type> 
        { 
            typeof(File), 
            typeof(string), 
            typeof(int), 
            typeof(bool) 
        };

        // 3. 按优先级列表排序
        var sortedProperties = properties
            .OrderBy(prop => 
            {
                // 获取当前属性类型在优先级列表中的索引
                int index = typePriority.IndexOf(prop.PropertyType);
                // 若不在列表中,返回列表长度,让它排在所有指定类型之后
                return index == -1 ? typePriority.Count : index;
            })
            // 可选:如果有同类型的属性,可追加ThenBy按属性名称二次排序
            .ThenBy(prop => prop.Name)
            .ToList();

        // 输出验证排序结果
        foreach (var prop in sortedProperties)
        {
            Console.WriteLine($"{prop.Name} - {prop.PropertyType.Name}");
        }
    }
}

代码说明

  • 动态调整规则:只需修改typePriority列表的内容或顺序,就能改变排序逻辑,完全满足你“排序规则可随指定类型列表改变”的需求。
  • 处理未指定类型:通过index == -1 ? typePriority.Count : index,让不在优先级列表中的属性自动排在所有指定类型之后,避免遗漏。
  • 二次排序扩展:如果存在多个同类型的属性,可通过ThenBy(prop => prop.Name)按属性名称排序,保证结果的稳定性。

内容的提问来源于stack exchange,提问作者Andrew Mooweek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 12:53:20