编程语言
首页 > 编程语言> > c# – 按customAttribute的值排序对象的属性

c# – 按customAttribute的值排序对象的属性

作者:互联网

我正在尝试做的是wirte linq表达式,它允许我订购我的List< PropertyInfo>例如,Custom属性的某个对象:

public class SampleClass{

   [CustomAttribute("MyAttrib1",1)]
   public string Name{ get; set; }
   [CustomAttribute("MyAttrib2",1)]
   public string Desc{get;set;}
   [CustomAttribute("MyAttrib1",2)]
   public int Price{get;set;}
}

CustomAttribute.cs:

public class CustomAttribute: Attribute{
    public string AttribName{get;set;}
    public int Index{get;set;}
    public CustomAttribute(string attribName,int index)
    {
        AttribName = attribName;
        Index = index;
    }
}

到目前为止,我能够从我的类中获取名为SampleClass的所有属性:

List<PropertyInfo> propertiesList = new List<PropertyInfo>((IEnumerable<PropertyInfo>)typeof(SampleClass).GetProperties());

到目前为止,我尝试对这个属性列表进行排序(btw不起作用):

var sortedPropertys = propertiesList
            .OrderByDescending(
                (x, y) => ((CustomAttribute) Attribute.GetCustomAttribute((PropertyInfo) x, typeof (CustomAttribute))).AttribName 
                .CompareTo((((CustomAttribute) Attribute.GetCustomAttribute((PropertyInfo) y, typeof (CustomAttribute))).AttribName ))
            ).OrderByDescending(
                (x,y)=>((CustomAttribute) Attribute.GetCustomAttribute((PropertyInfo) x, typeof (CustomAttribute))).Index
                .CompareTo((((CustomAttribute) Attribute.GetCustomAttribute((PropertyInfo) y, typeof (CustomAttribute))).Index)))
                .Select(x=>x);

输出列表应该是(我只用PropertyInfo.Name告诉它):

property name: Name,Price,Desc

我的问题是:有可能这样做吗?如果是,我该如何正确地做到这一点?

如果你有一些问题请问(我会尽力回答每一个不确定因素).我希望对问题的描述就足够了.

谢谢你提前:)

解决方法:

var props = typeof(SampleClass)
    .GetProperties()
    .OrderBy(p => p.GetCustomAttributes().OfType<CustomAttribute>().First().AttribName)
    .ThenBy(p => p.GetCustomAttributes().OfType<CustomAttribute>().First().Index)
    .Select(p => p.Name);

var propNames = String.Join(", ", props); 

输出:名称,价格,描述

标签:c,reflection,linq,linq-to-objects,c-4-0
来源: https://codeday.me/bug/20190613/1231333.html