計算機科学のブログ

enums and collections - Organizing your data - List, Sort, IComparer interface

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.433(Exercise)の解答を求めてみる。

コード

Program.cs

using ConsoleApp1;
using ConsoleApp4;
Random random = new Random();
Card RandomCard()
{
    return new Card((Values)random.Next(1, 14), (Suits)random.Next(4));
}
void PrintCards(List<Card> cards)
{
    foreach (Card card in cards)
    {
        Console.WriteLine(card.Name);
    }
}

Console.Write("Enter number of cards: ");
if (int.TryParse(Console.ReadLine(), out int number))
{
    List<Card> cards = new List<Card>();
    for (int i = 0; i < number; i++)
    {
        cards.Add(RandomCard());
    }
    PrintCards(cards);
    Console.WriteLine("... sorting the cards ...");
    cards.Sort(new CardComparerByValue());
    PrintCards(cards);
}
else
{
    Console.WriteLine("Invalid input.");
}

Card.cs

using System;

namespace ConsoleApp1;

public class Card
{
    public Values Value { get; }
    public Suits Suit { get; }
    public string Name
    {
        get { return $"{Value} of {Suit}"; }
    }

    public Card(Values value, Suits suit)
    {
        Value = value;
        Suit = suit;
    }
}

CardComparerByValue.cs

using ConsoleApp1;

namespace ConsoleApp4;

public class CardComparerByValue : IComparer<Card>
{
    public int Compare(Card? x, Card? y)
    {
        if (x.Suit > y.Suit)
        {
            return 1;
        }
        if (x.Suit < y.Suit)
        {
            return -1;
        }
        if (x.Value > y.Value)
        {
            return 1;
        }
        if (x.Value < y.Value)
        {
            return -1;
        }
        return 0;
    }
}

Suits.cs

namespace ConsoleApp1;

public enum Suits
{
    Diamonds,
    Clubs,
    Hearts,
    Spades,
}

Values.cs

namespace ConsoleApp1;

public enum Values
{
    Ace = 1,
    Two,
    Three,
    Four,
    Five,
    Six,
    Seven,
    Eight,
    Nine,
    Ten,
    Jack,
    Queen,
    King
}

入出力結果(Terminal, Zsh)

% dotnet run
/Users/kamimura/.../ConsoleApp4/CardComparerByValue.cs(9,13): warning CS8602: Dereference of a possibly null reference. [/Users/kamimura/.../ConsoleApp4/ConsoleApp4.csproj]
/Users/kamimura/.../ConsoleApp4/CardComparerByValue.cs(9,22): warning CS8602: Dereference of a possibly null reference. [/Users/kamimura/.../ConsoleApp4/ConsoleApp4.csproj]
Enter number of cards: 9
Three of Diamonds
Eight of Hearts
Eight of Spades
Six of Clubs
Five of Spades
Jack of Hearts
Nine of Hearts
Eight of Spades
Ace of Diamonds
... sorting the cards ...
Ace of Diamonds
Three of Diamonds
Six of Clubs
Eight of Hearts
Nine of Hearts
Jack of Hearts
Five of Spades
Eight of Spades
Eight of Spades
%