LINQ中的嵌套匿名类型

时间:2014-10-29 16:43:02

标签: c# linq

我正在尝试使用LINQ构建自定义结果集。目前,我有以下内容:

List<Team> teams = Team.FindAll();
List<Player> players = Player.FindAll();

var results = (from player in players
               select new
               {
                 PlayerId = player.Id,
                 PlayerName = player.Name,
                 Teams = teams.Where(t => player.TeamsIds.Contains(t.TeamId)).ToList() 
               });

我希望团队成为新的自定义类型。我希望该类型有一个名为IsChecked,TeamId和TeamName的字段。但是,每个团队目前只有TeamId和TeamName。如何在此LINQ语句中添加IsChecked属性?有没有办法筑巢&#34;选择新的&#34;声明?如果是这样,怎么样?

感谢?

1 个答案:

答案 0 :(得分:8)

当然,只需将其添加为投影:

var results = (from player in players
               select new
               {
                 PlayerId = player.Id,
                 PlayerName = player.Name,
                 Teams = teams.Where(t => player.TeamsIds.Contains(t.TeamId))
                              .Select(t => new {
                                                   t.TeamId,
                                                   t.TeamName,
                                                   IsChecked = ???
                                               }
                              .ToList() 
               });

或使用查询语法

var results = (from player in players
               select new
               {
                 PlayerId = player.Id,
                 PlayerName = player.Name,
                 Teams = (from t in teams
                          where player.TeamsIds.Contains(t.TeamId)
                          select new {
                                         t.TeamId,
                                         t.TeamName,
                                         IsChecked = ???
                                     }
                         ).ToList() 
               });