Lets say you had the following attribute definition
public class SortAttribute : Attribute {
public int Order { get; set; }
public SortAttribute(int order) { Order = order; }
}
You could use the following code to pull out the properties on a type in sorted order. Assuming of course they all have this attribute
public IEnumerable<object> GetPropertiesSorted(object obj) {
Type type = obj.GetType();
List<KeyValuePair<object,int>> list = new List<KeyValuePair<object,int>>();
foreach ( PropertyInfo info in type.GetProperties()) {
object value = info.GetValue(obj,null);
SortAttribute sort = (SortAttribute)Attribute.GetCustomAttribute(x, typeof(SortAttribute), false);
list.Add(new KeyValuePair<object,int>(value,sort.Order));
}
list.Sort(delegate (KeyValuePair<object,int> left, KeyValuePair<object,int> right) { left.Value.CompareTo right.Value; });
List<object> retList = new List<object>();
foreach ( var item in list ) {
retList.Add(item.Key);
}
return retList;
}
LINQ Style Solution
public IEnumerable<string> GetPropertiesSorted(object obj) {
var type = obj.GetType();
return type
.GetProperties()
.Select(x => new {
Value = x.GetValue(obj,null),
Attribute = (SortAttribute)Attribute.GetCustomAttribute(x, typeof(SortAttribute), false) })
.OrderBy(x => x.Attribute.Order)
.Select(x => x.Value)
.Cast<string>();
}