3

I am new to LINQ.

playerData is a list<DataAccess.Team> and I want to initialize another list of playerViewModelList with the data from playerData.

I tried foreach.

 foreach (DataAccess.Team dataTeam in playerData)
 {
     playerViewModelList.Add(new PlayersViewModel
     {
         PicPath = dataTeam.Tied.ToString(),
         PlayerID = (int)dataTeam.ID,
         PlayerName = dataTeam.TeamName
     });
  }

Is it possible to achieve the same thing using LINQ?

3 Answers 3

7

Select is the equivalent in this case:

playerViewModelList = playerData.Select(dataTeam => new PlayersViewModel
                                        {
                                            PicPath = dataTeam.Tied.ToString(),
                                            PlayerID = (int)dataTeam.ID,
                                            PlayerName = dataTeam.TeamName
                                        }).ToList();

Of course, this assumes playerViewModelList is a List<PlayersViewModel> or something similar. If you can't overwrite playerViewModelList, just stick with the foreach loop.

Sign up to request clarification or add additional context in comments.

Comments

5
playerData.ForEach(d => playerViewModelList.Add(new PlayersViewModel {
    PicPath = d.Tied.ToString(),
    PlayerID = (int)d.ID,
    PlayerName = d.TeamName
}));

or

playerViewModelList.AddRange(playerData.Select(d => new PlayersViewModel {
    PicPath = d.Tied.ToString(),
    PlayerID = (int)d.ID,
    PlayerName = d.TeamName
}));

Comments

0

Or, as you have List<> on both sides:

  playerViewModelList = playerData.ConvertAll(dataTeam => new PlayersViewModel
  {
    PicPath = dataTeam.Tied.ToString(),
    PlayerID = (int)dataTeam.ID,
    PlayerName = dataTeam.TeamName
  }); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.