計算機科学のブログ

enums and collections - Organizing your data - Sort, IComparable, ToString method, override

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

コード

Dog.cs

using System;

namespace MyFirstConsoleApp
{
    public class Dog: IComparable<Dog>
    {
        public Breeds Breed { get; set; }
        public string Name { get; set; }
        public Dog(Breeds breed, string name)
        {
            Breed = breed;
            Name = name;
        }
        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}";
        }
    }
}

コード

Program.cs

using System;
using System.Collections.Generic;

namespace MyFirstConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            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();
            List<string> vs = new List<string>()
            {
                "A Dachshund named Franz",
                "A Dachshund named Brunhilda",
                "A Collie named Zippy",
                "A Collie named Petunia",
                "A Pug named Porkchop",
                "A Corgi named Carrie",
            };
            for (int i = 0; i < dogs.Count; i++)
            {
                Console.WriteLine(dogs[i]);
                Console.WriteLine(dogs[i].ToString() == vs[i]);
            }
        }
    }
}

入出力結果(Terminal, Zsh)

A Dachshund named Franz
True
A Dachshund named Brunhilda
True
A Collie named Zippy
True
A Collie named Petunia
True
A Pug named Porkchop
True
A Corgi named Carrie
True