int IComparer <object> .Compare(object x, object y) { if (x is Duck && y is Duck) { Duck duckOne = (Duck)x; Duck duckTwo = (Duck)y; Console.WriteLine($"{duckOne.Name} is being compared to {duckTwo.Name}"); if (String.CompareOrdinal(duckOne.Name, duckTwo.Name) == 0) { Console.WriteLine($"{duckOne.Name} and {duckTwo.Name} are the same so we are ordering them now by weight"); if (duckOne.WeightInGrams > duckTwo.WeightInGrams) { Console.WriteLine($"{duckOne.Name} is above in weight by {duckOne.WeightInGrams} to {duckTwo.Name}'s {duckTwo.WeightInGrams}"); return(1); } else { Console.WriteLine($"{duckTwo.Name} is above in weight by {duckTwo.WeightInGrams} to {duckOne.Name}'s {duckOne.WeightInGrams}"); return(-1); } } else { if (String.Compare(duckOne.Name, duckTwo.Name, true) == 1) { Console.WriteLine($"{duckOne.Name} is higher in the alphabet compared to {duckTwo.Name}"); } if (String.Compare(duckOne.Name, duckTwo.Name, true) == -1) { Console.WriteLine($"{duckTwo.Name} is higher in the alphabet compared to {duckOne.Name}"); } return(String.Compare(duckOne.Name, duckTwo.Name, true)); } } else { throw new Exception("One or more objects are not object Duck"); } }
static void Main(string[] args) { var donald = new Duck("Sir Donald", "Mallard", 100, 17); var daffy = new Duck("Sir Daffy", "Mallard", 99, 14); var daisy = new Duck("Miss Daisy", "Marbled Duck", 38, 11); var anotherDaisy = new Duck("Sir Daisy", "Mallard", 99, 14); Console.WriteLine($"{donald.Name} has the hash code of {donald.GetHashCode()}"); Console.WriteLine($"{daffy.Name} has the hash code of {daffy.GetHashCode()}"); Console.WriteLine($"{daisy.Name} has the hash code of {daisy.GetHashCode()}"); Console.ReadLine(); Dictionary <Duck, int> ducks = new Dictionary <Duck, int> { { donald, donald.GetHashCode() }, { daffy, daffy.GetHashCode() }, { daisy, daisy.GetHashCode() } }; List <Duck> duckies = new List <Duck> { donald, daffy, daisy }; Console.WriteLine("The ducks have now been added to a list and sorted in name"); foreach (var duck in duckies) { Console.WriteLine(duck.Name); } duckies.Sort(new SortDuckHelper()); ToString(duckies); Console.ReadLine(); }