I want to sort the list of classes and interfaces. So my logic is
- if the class is not implemented interface it's higher than the interface, otherwise, it's lower
I am using the IComparer interface to sort my list. My model looks like this:
My Comparer class (if returns 1 it means y>x, 0 is x==y -1 is x>y):
public class SortedTypeComparer : IComparer<Type>
{
/// <summary>
/// Compares types
/// </summary>
public int Compare(Type x, Type y)
{
public int Compare(Type x, Type y)
{
if (y.IsAssignableFrom(x))
{
return 1;
}
else if (x.IsAssignableFrom(y))
{
return -1;
}
else if (!y.IsAssignableFrom(x) && !x.IsAssignableFrom(y) && x.IsInterface && y.IsClass)
{
return 1;
}
else if (!y.IsAssignableFrom(x) && !x.IsAssignableFrom(y) && x.IsClass && y.IsInterface)
{
return -1;
}
else
{
return 0;
}
}
}
}
I am expecting when I sort the list it should be:
IAnimal
IRunnable
Animal
ICat
Cat
Or:
IRunnable
IAnimal
Animal
ICat
Cat
Because IRunnable and IAnimal are 'equal'. Here is my usage:
var list = new List<Type>();
list.Add(typeof(IAnimal));
list.Add(typeof(IRunnable));
list.Add(typeof(ICat));
list.Add(typeof(Animal));
list.Add(typeof(Cat));
list.Sort(new SortedTypeComparer());
In this case, it is working as expected. But when I change the order of adding to list for example(put IRunnable to the end):
var list = new List<Type>();
list.Add(typeof(IAnimal));
list.Add(typeof(ICat));
list.Add(typeof(Animal));
list.Add(typeof(Cat));
list.Add(typeof(IRunnable));
list.Sort(new SortedTypeComparer());
The order is
IAnimal
Animal
ICat
IRunnable
Cat
It is not my expectation because of IRunnable>Animal. It seems when it compare Animal and ICat Animal is higher, then when it compares ICat and IRunnable it's saying "ICat == IRunnable, so Animal should be > IRunnable". How can I write the logic in the Compare method to sort my list as expected?
else if (!y.IsAssignableFrom(x) && !x.IsAssignableFrom(y) && x.IsInterface && y.IsClass)
- the first two seem redundand to me. They have already been checked.ComparTo(x, y)
should return1
whenx
is larger thany
.