LINQ and lambdas - Get Control of your data - join, anonymous types, var keyword
Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のChapter 9(LINQ and lambdas - Get Control of your data)、p.493(Sharpen your pencil)の解答を求めてみる。
コード
using System;
using System.Collections.Generic;
using System.Linq;
namespace MyFirstConsoleApp
{
class Program
{
static void Main(string[] args)
{
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 = .75M },
new {Name = "Alice", Round=4, Winnings = 1.3M },
new {Name = "Alice", Round = 5 , Winnings=.7M },
new {Name = "Joe", Round = 6, Winnings = 1M },
};
var playersStats =
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,
};
var names = new[] {
"Alice", "Alice", "Alice",
"Bob",
"Joe", "Joe",
};
var yearsPlayed = new[]
{
11, 11, 11,
5,
7, 7,
};
var globalRanks = new[]
{
17, 17, 17,
13,
21, 21,
};
var rounds = new[]
{
2, 4, 5,
3,
1, 6,
};
var winnings = new[]
{
2M, 1.3M, .7M,
.75M,
1.5M, 1M,
};
int i = 0;
foreach (var stat in playersStats)
{
Console.WriteLine(stat);
Console.WriteLine(
"{0}, {1}, {2}, {3}, {4}",
stat.Name == names[i],
stat.YearsPlayed == yearsPlayed[i],
stat.GlobalRank == globalRanks[i],
stat.Round == rounds[i],
stat.Winnings == winnings[i]);
i++;
}
}
}
}
入出力結果(Terminal, Zsh)
{ Name = Alice, YearsPlayed = 11, GlobalRank = 17, Round = 2, Winnings = 2 }
True, True, True, True, True
{ Name = Alice, YearsPlayed = 11, GlobalRank = 17, Round = 4, Winnings = 1.3 }
True, True, True, True, True
{ Name = Alice, YearsPlayed = 11, GlobalRank = 17, Round = 5, Winnings = 0.7 }
True, True, True, True, True
{ Name = Bob, YearsPlayed = 5, GlobalRank = 13, Round = 3, Winnings = 0.75 }
True, True, True, True, True
{ Name = Joe, YearsPlayed = 7, GlobalRank = 21, Round = 1, Winnings = 1.5 }
True, True, True, True, True
{ Name = Joe, YearsPlayed = 7, GlobalRank = 21, Round = 6, Winnings = 1 }
True, True, True, True, True