我是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实现相同的功能?
答案 0 :(得分: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
循环。
答案 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
});