3

我是 LINQ 的新手。

playerData是一个list<DataAccess.Team>,我想playerViewModelList用来自 的数据初始化另一个列表playerData

我试过了foreach

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

是否可以使用 LINQ 实现相同的目标?

4

3 回答 3

7

Select在这种情况下是等价的:

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

当然,这假设playerViewModelList是一个List<PlayersViewModel>或类似的东西。如果你不能覆盖playerViewModelList,就坚持foreach循环。

于 2012-06-20T22:08:55.827 回答
5
playerData.ForEach(d => playerViewModelList.Add(new PlayersViewModel {
    PicPath = d.Tied.ToString(),
    PlayerID = (int)d.ID,
    PlayerName = d.TeamName
}));

或者

playerViewModelList.AddRange(playerData.Select(d => new PlayersViewModel {
    PicPath = d.Tied.ToString(),
    PlayerID = (int)d.ID,
    PlayerName = d.TeamName
}));
于 2012-06-20T22:10:07.130 回答
0

或者,正如您List<>在双方所拥有的那样:

  playerViewModelList = playerData.ConvertAll(dataTeam => new PlayersViewModel
  {
    PicPath = dataTeam.Tied.ToString(),
    PlayerID = (int)dataTeam.ID,
    PlayerName = dataTeam.TeamName
  }); 
于 2012-06-21T12:40:12.817 回答