計算機科学のブログ

enums and collections - Organizing your data - ToString method, override, list, IComparable interface, CompareTo method, reverse

Head First C Sharp: A Learner’s Guide to Real-World Programming with C Sharp and .NET (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)の Chapter 8(enums and collections - Organizing your data)、p.437(Sharpen your pencil)の解答を求めてみる。

コード

Program.cs

List<Dog> dogs = new List<Dog>()
{
    new Dog(Breeds.Dachshund,  "Franz"),
    new Dog(Breeds.Collie, "Petunia"),
    new Dog(Breeds.Pug, "Porkchop"),
    new Dog(Breeds.Dachshund, "Brunhilda"),
    new Dog(Breeds.Collie, "Zippy"),
    new Dog(Breeds.Corgi,"Carrie"),
};
dogs.Sort();
// new Dog(Breeds.Dachshund, "Brunhilda")
// new Dog(Breeds.Collie, "Zippy")
// new Dog(Breeds.Collie, "Petunia")
// new Dog(Breeds.Pug, "Porkchop")
// new Dog(Breeds.Corgi,"Carrie")
foreach (Dog dog in dogs)
{
    Console.WriteLine(dog);
}
enum Breeds
{
    Collie = 3,
    Corgi = -9,
    Dachshund = 7,
    Pug = 0,
}
class Dog : IComparable<Dog>
{
    public Breeds Breed { get; set; }
    public string Name { get; set; }
    public int CompareTo(Dog? other)
    {
        if (Breed > other?.Breed)
        {
            return -1;
        }
        if (Breed < other?.Breed)
        {
            return 1;
        }
        return -Name.CompareTo(other?.Name);
    }
    public override string ToString()
    {
        return $"A {Breed} named {Name}";
    }
    public Dog(Breeds breed, string name)
    {
        Breed = breed;
        Name = name;
    }
}

入出力結果(Terminal, Zsh)

% dotnet run
A Dachshund named Franz
A Dachshund named Brunhilda
A Collie named Zippy
A Collie named Petunia
A Pug named Porkchop
A Corgi named Carrie
%