Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Anonymous Type in LINQ

Tags:

c#

linq

I am trying to build custom result set with LINQ. Currently, I have the following:

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

I want Teams to be a new custom type. I want the type to have a field called IsChecked, TeamId, and TeamName. However, each Team currently only has TeamId and TeamName. How do I get an IsChecked property added within this LINQ statement? Is there a way to nest "select new" statements? If so, how?

Thanks?

like image 937
JQuery Mobile Avatar asked Dec 26 '22 02:12

JQuery Mobile


1 Answers

Sure, just add that as a projection:

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

or using query syntax

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() 
               });
like image 55
D Stanley Avatar answered Dec 27 '22 19:12

D Stanley