計算機科学のブログ

LINQ and lambdas - Get control of your data - anonymous types, list, query(join, on, equals)

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.493(Sharpen your pencil)の解答を求めてみる。

コード

Program.cs

var players = new[]
{
    new {Name="Joe", YearsPlayed=7, GlobalRank=21},
    new {Name="Bob", YearsPlayed=5, GlobalRank=13},
    new {Name="Alice", YearsPlayed=11, GlobalRank=17},
};
var playerWins = new[]
{
    new {Name="Joe",Round=1,Winnings=1.5M},
    new {Name="Alice",Round=2,Winnings=2M},
    new {Name="Bob",Round=3,Winnings=0.75M},
    new {Name="Alice",Round=4,Winnings=1.3M},
    new {Name="Alice",Round=5,Winnings=0.7M},
    new {Name="Joe",Round=6,Winnings=1M},
};
var playerStats =
    from player in players
    join win in playerWins
    on player.Name equals win.Name
    orderby player.Name
    select new
    {
        Name = player.Name,
        YearsPlayed = player.YearsPlayed,
        GlobalRank = player.GlobalRank,
        Round = win.Round,
        Winnings = win.Winnings,
    };

// Alice, 11, 17, 2, 2M
// Alice,         4, 1.3M
// Alice,         5, 0.7M
// Bob, 5, 13, 3, 0.75M 
// Joe, 7, 21, 1, 1.5M
// Joe,        6, 1M
foreach (var state in playerStats)
{
    Console.WriteLine(state);
}

入出力結果(Terminal, Zsh)

% dotnet run
{ Name = Alice, YearsPlayed = 11, GlobalRank = 17, Round = 2, Winnings = 2 }
{ Name = Alice, YearsPlayed = 11, GlobalRank = 17, Round = 4, Winnings = 1.3 }
{ Name = Alice, YearsPlayed = 11, GlobalRank = 17, Round = 5, Winnings = 0.7 }
{ Name = Bob, YearsPlayed = 5, GlobalRank = 13, Round = 3, Winnings = 0.75 }
{ Name = Joe, YearsPlayed = 7, GlobalRank = 21, Round = 1, Winnings = 1.5 }
{ Name = Joe, YearsPlayed = 7, GlobalRank = 21, Round = 6, Winnings = 1 }
%