計算機科学のブログ

LINQ and lambdas - Get control of your data - switch expressions

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 9(LINQ and lambdas - Get control of your data)、p.518(Sharpen your pencil)の解答を求めてみる。

コード

Program.cs

using ConsoleApp1;

var deck = new Deck();
foreach (var item in deck)
{
    Console.WriteLine(item);
}
// D1, D2, D3
// D1, D2, D3, S11, S12, S13
// S13, S12, S11, D3, D2, D1,
// Suit is Spades and number is 7
// Queen of Spades
// Suit is Hearts and number is 9
// Three of Diamonds
// Suit is Diamonds and number is 18
// It's an ace! Diamonds
var processedCards = deck
    .Take(3)
    .Concat(deck.TakeLast(3))
    .OrderByDescending(card => card)
    .Select(card => card.Value switch
    {
        Values.King => Output(card.Suit, 7),
        Values.Ace => $"It's an ace! {card.Suit}",
        Values.Jack => Output((Suits)card.Suit - 1, 9),
        Values.Two => Output(card.Suit, 18),
        _ => card.ToString()
    });
foreach (var item in processedCards)
{
    Console.WriteLine(item);
}

string Output(Suits suit, int number) => $"Suit is {suit} and number is {number}";

入出力結果(Terminal, Zsh)

% dotnet run
Ace of Diamonds
Two of Diamonds
Three of Diamonds
Four of Diamonds
Five of Diamonds
Six of Diamonds
Seven of Diamonds
Eight of Diamonds
Nine of Diamonds
Ten of Diamonds
Jack of Diamonds
Queen of Diamonds
King of Diamonds
Ace of Clubs
Two of Clubs
Three of Clubs
Four of Clubs
Five of Clubs
Six of Clubs
Seven of Clubs
Eight of Clubs
Nine of Clubs
Ten of Clubs
Jack of Clubs
Queen of Clubs
King of Clubs
Ace of Hearts
Two of Hearts
Three of Hearts
Four of Hearts
Five of Hearts
Six of Hearts
Seven of Hearts
Eight of Hearts
Nine of Hearts
Ten of Hearts
Jack of Hearts
Queen of Hearts
King of Hearts
Ace of Spades
Two of Spades
Three of Spades
Four of Spades
Five of Spades
Six of Spades
Seven of Spades
Eight of Spades
Nine of Spades
Ten of Spades
Jack of Spades
Queen of Spades
King of Spades
Suit is Spades and number is 7
Queen of Spades
Suit is Hearts and number is 9
Three of Diamonds
Suit is Diamonds and number is 18
It's an ace! Diamonds
%