Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of For Loop in LINQ

Tags:

c#

.net

linq

c#-4.0

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?

like image 961
kbvishnu Avatar asked Dec 19 '25 11:12

kbvishnu


2 Answers

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.

like image 58
Ry- Avatar answered Dec 22 '25 02:12

Ry-


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
}));
like image 41
Ilya Kozhevnikov Avatar answered Dec 22 '25 04:12

Ilya Kozhevnikov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!