0

I have a List<> of type GameResult that I want to populate with a new instance of the class GameResult using data from an array(gamerArray).

So I have this using a foreach loop.

 List<GameResult> gameResults = new List<GameResult>();
 foreach (var g in gamerArray.GamePlayers)
        {
            gameResults.Add(
                new GameResult
                {
                    GameID = g.GameID,
                    GameName = g.GameName,
                    SessionStart = g.StartTime,
                    SessionEnd = g.EndTime,
                    SessionMessage = "You Won!"
                });
        }

Is there a way to use Linq to iterate over the array and create the new List of GameResult objects?

Thanks

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
SkyeBoniwell
  • 6,345
  • 12
  • 81
  • 185

2 Answers2

1

Try this:

List<GameResult> gameResults = gamerArray.GamePlayers.Select(g => new GameResult
{
    GameID = g.GameID,
    GameName = g.GameName,
    SessionStart = g.StartTime,
    SessionEnd = g.EndTime,
    SessionMessage = "You Won!"
}).ToList();
mm8
  • 163,881
  • 10
  • 57
  • 88
0
gameResults = gamerArray.GamePlayers.Select(g => new GameResult
                {
                    GameID = g.GameID,
                    GameName = g.GameName,
                    SessionStart = g.StartTime,
                    SessionEnd = g.EndTime,
                    SessionMessage = "You Won!"
                }).ToList();

Linq Select

Matt.G
  • 3,586
  • 2
  • 10
  • 23