Question:
There is an array of objects derived from the Car
class: PassengerCar
, FreightCar
, and SpecializedFreightCar
.
You need to sort the array by the types of heirs. For example, PassengerCar
objects come first, then FreightCar
, then SpecializedFreightCar
.
PassengerCar
and FreightCar
inherit traits from the Car
class.
SpecializedFreightCar
inherits traits from the FreightCar
class.
Answer:
If sorting can be used in multiple places, I recommend writing a Comparer, like so:
class CarComparer : IComparer<Car>
{
static Dictionary<Type, int> priorities = new Dictionary<Type, int>();
static CarComparer()
{
priorities.Add(typeof(PassengerCar), 1);
priorities.Add(typeof(FreightCar), 2);
priorities.Add(typeof(SpecializedFreightCar), 3);
}
int PriorityFor(Type type)
{
priorities.TryGetValue(type, out int p);
return p;
}
public int Compare(Car x, Car y)
{
int priorityX = PriorityFor(x.GetType());
int priorityY = PriorityFor(y.GetType());
return priorityX.CompareTo(priorityY);
}
}
Usage example:
Car[] cars =
{
new SpecializedFreightCar(),
new FreightCar(),
new FreightCar(),
new PassengerCar(),
new SpecializedFreightCar()
};
Array.Sort(cars, new CarComparer());
Console.WriteLine(string.Join<Car>("\n", cars));
Code copied almost verbatim from Agile Principles, Patterns, and Techniques in C# by Robert Martin, Mika Martin