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?
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.
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
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With