Demodave Demodave - 2 months ago 6
C# Question

Sort properties given attribute paramter order

I want to sort properties based off an attribute parameter

Order
that is given.

Attribute:

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


Implementation:

public class client
{
[Items(1)]
public string fName {get; set;}

[Items(3)]
public string lName {get; set;}

[Items(2)]
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

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.

Comments