按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);
但我得到"无法从用法推断"错误。
使用以下方法工作:
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();