Tuesday, September 5, 2017

Difference between Select and SelectMany in LINQ

Select and SelectMany are projection operator and Select method is used to select a
value from collection and SelectMany method is used to select value from multiple
collection. 

In below example, we will see that Select will returns the collection of Player object and to read Player Name, we need one more For Each loop to read the Player object and
SelectMany will flatten the list into a single list of Players, so we need only one for-each
loop to get player name.

Select Vs Select Many


C# Example : 


List<Team> teams = new List<Team>();


Team team1 = new Team {
             Name = "USA",
             Players = new List<Player> {
                                     new Player {  PlayerName = "John" },
                                     new Player { PlayerName = "Peter" },
                                     new Player { PlayerName = "Steve" }
             } };


Team team2 = new Team
         {
             Name = "AUS",
             Players = new List<Player> {
                    new Player {  PlayerName = "Ricky" },
                    new Player { PlayerName = "McGraw" },
                    new Player { PlayerName = "Donald" }
             }
         };


teams.Add(team1);
teams.Add(team2);


Select : 
by using Select query. We need two for-each loop to retrieve the player name from a
team collection of arrays, because Select returns a collection of arrays.


C# Example : 


var resultSelect = teams.Select(e => e.Players);


foreach (var playerList in resultSelect)
         {
                foreach (var player in playerList)
             {                      Console.WriteLine(player.PlayerName);
             }
                Console.WriteLine();
         }


Output:


John
Peter
Steve


Ricky
McGraw
Donald


SelectMany: 
By using SelectMany query, we only need one for each loop to retrieve the player name
from team collection of array and SelectMany returns a one dimensional collection.

C# Example : 
     
      var resultSelectMany = teams.SelectMany(emp => emp.Players);


      foreach (var player in resultSelectMany)
         {
                Console.WriteLine(player.PlayerName);
         }


            Console.ReadKey();
     }


Output:
John
Peter
Steve
Ricky
McGraw
Donald


Thanks for visiting !!

No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...