Difference Between Select and SelectMany

后端 未结 17 1399
长情又很酷
长情又很酷 2020-11-22 05:21

I\'ve been searching the difference between Select and SelectMany but I haven\'t been able to find a suitable answer. I need to learn the differenc

17条回答
  •  忘掉有多难
    2020-11-22 05:27

    There are several overloads to SelectMany. One of them allows you to keep trace of any relationship between parent and children while traversing the hierarchy.

    Example: suppose you have the following structure: League -> Teams -> Player.

    You can easily return a flat collection of players. However you may lose any reference to the team the player is part of.

    Fortunately there is an overload for such purpose:

    var teamsAndTheirLeagues = 
             from helper in leagues.SelectMany
                   ( l => l.Teams
                     , ( league, team ) => new { league, team } )
                          where helper.team.Players.Count > 2 
                               && helper.league.Teams.Count < 10
                               select new 
                                      { LeagueID = helper.league.ID
                                        , Team = helper.team 
                                       };
    

    The previous example is taken from Dan's IK blog. I strongly recommend you take a look at it.

提交回复
热议问题