Let me implement a simple method to get how deep a class is in the class hierarchy.
null <- object <- ... <- MyBaseClass <- MyClass <- ...
Implementation
private static int TypeLevel(Type type) {
if (null == type)
return 0;
return TypeLevel(type.BaseType) + 1;
}
And then using Linq sorting by this criterion, the only little trick is to use DeclaringType
- where (in which class) the property was declared:
string[] fieldNames = typeof(MyClass)
.GetProperties()
.OrderBy(p => TypeLevel(p.DeclaringType))
.ThenBy(p => p.Name)
.Select(p => p.Name)
.ToArray();
Console.Write(string.Join(Environment.NewLine, fieldNames));
Result:
BaseField1
BaseField2
BaseField3
BaseField4
Field1
Field2
Field3
Field4
Finally, your method might be something like this:
private void MyMethod<T>(List<T> listData) {
...
string[] fieldNames = typeof(T)
.GetProperties()
.OrderBy(p => TypeLevel(p.DeclaringType))
.ThenBy(p => p.Name)
.Select(p => p.Name)
.ToArray();
...
}