Demodave
Demodave

Reputation: 6632

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?

This has been solved, but would like to extend the question.

Is there a way to sort properties without having to put an "Order" on them. I am wanting to just have an attribute "EndOfList" Or "Last" that would state be sure to sort these last. So that I would not have to clutter up the code with Orders.

Upvotes: 0

Views: 133

Answers (2)

Abhinav Galodha
Abhinav Galodha

Reputation: 9878

You can try this

var properties = typeof(client).GetProperties().Where(prop => prop.IsDefined(typeof(Items), false));
var sortedProperties = properties.OrderBy(x =>  ((Items)x.GetCustomAttributes(typeof(Items), false).FirstOrDefault()).Order);

Upvotes: 1

PiotrWolkowski
PiotrWolkowski

Reputation: 8782

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.

Upvotes: 1

Related Questions