2012-06-20 87 views
3

我是LINQ的新手。LINQ中For循環的等效代碼

playerDatalist<DataAccess.Team>,我想用playerData的數據初始化另一個playerViewModelList列表。我試過foreach

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

使用LINQ可以達到同樣的效果嗎?

回答

7

Select在這種情況下,相當於:

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

。當然,這是假定playerViewModelListList<PlayersViewModel>或類似的東西。如果您不能覆蓋playerViewModelList,只需使用foreach循環即可。

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 
})); 
0

或者,你有兩面List<>

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