Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Sorting Type hierarchy

Tags:

c#

reflection

I have multiple Types stored in a list, and I need to have them sorted from the most concrete type to the most general ones, example:

Vehicle
  Car
  Bike

Person
  Manager
  Programmer

So it makes list with: Vehicle, Car, Bike, Person, Manager, Programmer types. Now I need to get ordered list where more concrete type is always before more general type like: Car, Bike, Vehicle, Manager, Programmer, Person. Is there some simple/elegant way to achieve this, besides some gymnastics with Type.IsAssignableFrom ?

like image 346
Jarek Avatar asked Nov 18 '25 18:11

Jarek


1 Answers

One simple way is to figure that every child class must have more classes in its hierachy than its parents do, so you can order by how many classes are in each type's hierarchy:

var types = new[] {
    typeof(Vehicle),
    typeof(Car),
    typeof(Bike),
    typeof(Person),
    typeof(Manager),
    typeof(Programmer)
};
var ordered = types.OrderByDescending(t => GetHierarchy(t).Count());

Using this:

private static IEnumerable<Type> GetHierarchy(Type type)
{
    while (type != null) {
        yield return type;
        type = type.BaseType;
    }
}

class Vehicle {}
  class Car : Vehicle{}
  class Bike : Vehicle{}

class Person {}
  class Manager : Person{}
  class Programmer : Person{}
like image 188
StriplingWarrior Avatar answered Nov 20 '25 08:11

StriplingWarrior



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!