How to use reflection to get base class properties before derived class properties

public class BaseDto
{
    public int ID{ get; set; }
}
public class Client: BaseDto
{
     public string Surname { get; set; }
     public string FirstName{ get; set; }
     public string email{ get; set; }    
}

PropertyInfo[] props = typeof(Client).GetProperties();

The properties are listed in the following order: Last Name, FirstName, email, ID

Want the properties to be displayed in the following order: ID, Last Name, FirstName, Email

+4
source share
4 answers

Maybe this?

// this is alternative for typeof(T).GetProperties()
// that returns base class properties before inherited class properties
protected PropertyInfo[] GetBasePropertiesFirst(Type type)
{
    var orderList = new List<Type>();
    var iteratingType = type;
    do
    {
        orderList.Insert(0, iteratingType);
        iteratingType = iteratingType.BaseType;
    } while (iteratingType != null);

    var props = type.GetProperties()
        .OrderBy(x => orderList.IndexOf(x.DeclaringType))
        .ToArray();

    return props;
}
+8
source

Not sure if there is a faster way to do this, but first get the type of the base type that you inherit from.

    typeof(Client).BaseType

After that, you can only get basic properties using bindflags.

    BindingFlags.DeclaredOnly

After that, do the same for the Client type and add the result.

+1
source

linq:

var baseProps = typeof(BaseDto).GetProperties();
var props = typeof(Client).GetProperties();

var allProps = baseProps
   .Concat(props.Where(p => baseProps
      .Select(b => b.Name)
      .Contains(p.Name) == false));
+1

:

Dictionary<string, PropertyInfo> _PropertyIndex = new Dictionary<string, PropertyInfo>();

Type thisType = typeof(Client);

foreach (PropertyInfo pi in thisType.BaseType.GetProperties())
    _PropertyIndex.Add(pi.Name.ToUpper(), pi);
foreach (PropertyInfo pi in thisType.GetProperties())
    if( !_PropertyIndex.ContainsKey(pi.Name.ToUpper()))
        _PropertyIndex.Add(pi.Name.ToUpper(), pi);
0

All Articles