Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order properties of object by value of customAttribute

What I'm trying to do is wirte linq expression which allows me to order my List<PropertyInfo> of some object by Custom attribute for example:

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;
    }
}

so far I was able to get all properties from my class named SampleClass:

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

my tryed so far to sort this propertiesList (which btw doesn't work) :

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);

Output List should be (I'll tell it only with PropertyInfo.Name):

property name: Name,Price,Desc

My question is: Is it possible to do that? And If yes how can I do this properly?

If you have some question pls ask (I'll do my best to answer every uncertainties). I hope description of problem is enough.

Thanks for advance:)

like image 535
Harry89pl Avatar asked Oct 29 '12 16:10

Harry89pl


1 Answers

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); 

OUTPUT: Name, Price, Desc

like image 171
L.B Avatar answered Oct 01 '22 01:10

L.B