Demodave Demodave - 1 year ago 83
C# Question

Sort properties given attribute paramter order

I want to sort properties based off an attribute parameter

that is given.


public class Items: Attribute
public int Order { get; set; }
public Items(int order)
this.Order = order;


public class client
public string fName {get; set;}

public string lName {get; set;}

public string mName {get; set;}

Get all Properties:

var properties = typeof(client).GetProperties().Where(
prop => prop.IsDefined(typeof(Items), false));

Sort by Order#?

This is what I tried but it does not work

Array.Sort(properties, delegate (Items x, Items y)
{ return x.Order.CompareTo(y.Order); });

How do I sort the properties based off the Order?

Answer Source

You can use Linq and OrderBy

var sorted = properties
    .OrderBy(p => ((Items)p.GetCustomAttributes(true)
                           .FirstOrDefault(a => a is Items)).Order);

This results in following order: fName, mName, lName.

So what happens inside the OrderBy: access custom properties. Find a first that is of type Items and use the Order property as a sort parameter.

To sort in reversed order just use OrderByDescending.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download