without using GroupJoin:
var playersDictionary = players.ToDictionary(player => player.Id,
element => new PlayerDto { Rounds = new List<RoundDto>() });
foreach (var round in rounds)
{
PlayerDto playerDto;
playersDictionary.TryGetValue(round.PlayerId, out playerDto);
if (playerDto != null)
{
playerDto.Rounds.Add(new RoundDto { });
}
}
var playerDtoItems = playersDictionary.Values;
using GroupJoin:
var playerDtoItems =
from player in players
join round in rounds
on player.Id equals round.PlayerId
into playerRounds
select new PlayerDto { Rounds = playerRounds.Select(playerRound => new RoundDto {}) };
Which of these two pieces is more efficient?
Without testing, you really can’t know. As a rule of thumb, anything done in LINQ is slower than the same thing done manually; the extra iterators and delegate invocations do have their costs.
However, for most practical purposes I would consider them equal in performance. If the performance really makes a difference (i.e. you are in a very critical block, or you notice a slowdown), you will definitely want to measure.