I'm trying to rearrange a list of animals in order from medium, large, small. I've been trying to do this with IComparable.CompareTo but I can't figure out how to order it in this specific way. I can only find ways to order by Ascending or Descending values.
My enum:
public enum AnimalSize
{
Small = 1, Medium = 3, Large = 5,
}
My Animal class:
public class Animal : IComparable<Animal>
{
public bool IsCarnivore;
public AnimalSize Size;
public Animal(bool isCarnivore, AnimalSize size)
{
this.IsCarnivore = isCarnivore;
this.Size = size;
}
public int CompareTo(Animal other)
{
return this.Size.CompareTo(other.Size);
}
I call the CompareTo from another class where I have a private list of animals.
How can I arrange the animals in order of Medium, Large, Small?
I would not implement IComparable<T> for a non-scalar object such as an animal. What if you want to sort by height instead of size? Or by name? IComparable implies that the object can be converted to a one-dimensional quantity.
Instead, define the sort order you need in an array, and use a simple LINQ query to sort.
public static void Main()
{
var sampleData = new List<Animal>
{
new Animal(false, AnimalSize.Small),
new Animal(false, AnimalSize.Large),
new Animal(false, AnimalSize.Medium)
};
AnimalSize[] customSortOrder = new[]
{
AnimalSize.Small,
AnimalSize.Medium,
AnimalSize.Large
};
var results = sampleData.OrderBy( a => Array.IndexOf(customSortOrder, a.Size ));
foreach (var a in results)
{
Console.WriteLine(a.Size);
}
Output:
Small
Medium
Large
Code on DotNetFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With