0

I have a dictionary. It contains Type and string:

 var myDictionary = new Dictionary<Type, string>();
        myDictionary.Add(typeof(Person), "Person");
        myDictionary.Add(typeof(IPerson), "IPerson");
        myDictionary.Add(typeof(IGoodStudent), "IGoodStudent");
        myDictionary.Add(typeof(IStudent), "IStudent");
        myDictionary.Add(typeof(GoodStudent), "GoodStudent");
        myDictionary.Add(typeof(Student), "Student");

And my inheritance tree :

Inheritance tree

I want to sort my dictionary by dependency. First, it should look at inheritance then at implementation. In this case, my expectation is :

IPerson
Person
IStudent
Student
IGoodStudent
GoodStudent

How can I sort my dictionary?

Dilshod K
  • 2,924
  • 1
  • 13
  • 46
  • "How can I sort my dictionary?" Not at all, unless you use `SortedDictionary`. A `Dictionary` does never gurantee any order. – MakePeaceGreatAgain Sep 03 '19 at 09:31
  • Why is `Person` before `IStudent`? `IStudent` inherits `IPerson` where `Person` implements it, so from your description I would assume their ordering to be the other way around? So shouldn't it be `IPerson, IStudent, IGoodStudent, Person, Student, GoodStudent`? –  Sep 03 '19 at 09:45
  • @Knoop "IStudent inherits IPerson" is it correct? I think, "IStudent implements IPerson" is most suitable in this case – Dilshod K Sep 03 '19 at 09:49
  • 1
    @DIlshodK an `Interface` by it's very definition can not implement anything. So no, I would say `IStudent implements IPerson` is not how it works, neither `IStudent` nor `IPerson` implement anything. –  Sep 03 '19 at 09:52

1 Answers1

2

You could create a sorted dictionary and use a custom IComparer:

SortedDictionary<Type, string> myDictionary= new SortedDictionary<Type, string>(new SortedTypeComparer());
myDictionary.Add(typeof(Person), "Person");
// Etc....

With the custom IComparer like so:

public class SortedTypeComparer : IComparer<Type>
{
  public int Compare(Type x, Type y)
  {
    // Logic here to compare the types however you wish
    // - If less than 0, x is less than y.
    // - If 0, x equals y.
    // - If greater than 0, x is greater than y
  }
}
andyb952
  • 1,931
  • 11
  • 25