If you intend to use the attribute route, the method that I used in the past is used here;
public static IOrderedEnumerable<PropertyInfo> GetSortedProperties<T>() { return typeof(T) .GetProperties() .OrderBy(p => ((Order)p.GetCustomAttributes(typeof(Order), false)[0]).Order); }
Then use it as follows:
var test = new TestRecord { A = 1, B = 2, C = 3 }; foreach (var prop in GetSortedProperties<TestRecord>()) { Console.WriteLine(prop.GetValue(test, null)); }
Where
class TestRecord { [Order(1)] public int A { get; set; } [Order(2)] public int B { get; set; } [Order(3)] public int C { get; set; } }
The method will be barf if you run it by type without comparable attributes across all your properties, so be careful how it is used, and this should be enough for the requirement.
I declined the definition of Order: Attribute, since Yahia has a good sample link to Mark Gravell’s post.
Christopher McAtackney Jan 30 2018-12-01T00: 00Z
source share