按PropertyInfos属性的属性值对其列表进行排序

本文关键字:属性 列表 排序 PropertyInfos | 更新日期: 2023-09-27 18:20:35

我有一个类型为的Dto对象

public class ClassA
{       
    [DataMember(Order = 10)]
    public string Code { get; set; }
    [DataMember(Order = 20)]
    public string Symbology { get; set; }
    [DataMember(Order = 30)]
    public string Category { get; set; }
    public string NonMemberPropertyA { get; set; }
}

我有兴趣获得所有DataMember装饰的属性:

 var propertyInfos = type.GetProperties().Where(p => Attribute.IsDefined(p, typeof (DataMemberAttribute)));

现在我需要根据DataMember属性的Order属性对propertyInfos进行排序。因为有些可能出了问题。

所以我试着添加:

.OrderBy(p => ((DataFormat)Attribute.GetCustomAttribute(p, typeof (DataFormat))).Order);

但我得到"无法从用法推断"错误。

按PropertyInfos属性的属性值对其列表进行排序

使用以下方法工作:

var orders = a1
    .GetType()
    .GetProperties()
    .Where(x => Attribute.IsDefined(x, typeof(DataMemberAttribute)))
    .Select(x => new { Att = x.GetCustomAttribute<DataMemberAttribute>(true), Prop = x })
    .OrderBy(x => x.Att.Order);

Select()投影一个由属性本身和属性组成的匿名对象,这样您就可以按属性排序。

a1是对象ClassA 的实例

我修改了你的代码并使其工作:

var orders = a1
    .GetType()
    .GetProperties()
    .Where(p => Attribute.IsDefined(p, typeof(DataMemberAttribute)))
    .OrderBy(p => ((DataMemberAttribute)Attribute.GetCustomAttribute(p, typeof(DataMemberAttribute))).Order);

这样做:

var propertyInfos = type
            .GetProperties(BindingFlags.Public | BindingFlags.NonPublic)
            .Where(m => m.GetCustomAttributes(typeof(DataMemberAttribute), false).Length > 0)
            .SelectMany(m => m.GetCustomAttributes(false).OfType<DataMemberAttribute>())
            .OrderBy(m => m.Order)
            .ToArray();