在LINQ中等效For循环

时间:2012-06-20 22:05:11

标签: c# .net linq c#-4.0

我是LINQ的新手。

playerDatalist<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实现相同的功能?

3 个答案:

答案 0 :(得分:7)

在这种情况下,

Select是等效的:

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

当然,这假定playerViewModelListList<PlayersViewModel>或类似的东西。如果您无法覆盖playerViewModelList,请坚持使用foreach循环。

答案 1 :(得分: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
}));

答案 2 :(得分:0)

或者,因为双方都有List<>

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