HI WELCOME TO SIRIS

Difference between Select and SelectMany in LINQ

Select and SelectMany are projection operators. Select operator is used to select value from a collection and SelectMany operator is used to select values from a collection of collection i.e. nested collection.
Select operator produce one result value for every source value while SelectMany produce a single result that contains a concatenated value for every source value. Actually, SelectMany operator flatten IEnumerable<IEnumerable<T>> to IEnumrable<T> i.e. list of list to list.
  1. class Employee
  2. {
  3. public string Name { get; set; }
  4. public List<string> Skills { get; set; }
  5. }
  6.  
  7. class Program
  8. {
  9. static void Main(string[] args)
  10. {
  11. List<Employee> employees = new List<Employee>();
  12. Employee emp1 = new Employee { Name = "Deepak", Skills = new List<string> { "C", "C++", "Java" } };
  13. Employee emp2 = new Employee { Name = "Karan", Skills = new List<string> { "SQL Server", "C#", "ASP.NET" } };
  14.  
  15. Employee emp3 = new Employee { Name = "Lalit", Skills = new List<string> { "C#", "ASP.NET MVC", "Windows Azure", "SQL Server" } };
  16.  
  17. employees.Add(emp1);
  18. employees.Add(emp2);
  19. employees.Add(emp3);
  20.  
  21. // Query using Select()
  22. IEnumerable<List<String>> resultSelect = employees.Select(e=> e.Skills);
  23.  
  24. Console.WriteLine("**************** Select ******************");
  25.  
  26. // Two foreach loops are required to iterate through the results
  27. // because the query returns a collection of arrays.
  28. foreach (List<String> skillList in resultSelect)
  29. {
  30. foreach (string skill in skillList)
  31. {
  32. Console.WriteLine(skill);
  33. }
  34. Console.WriteLine();
  35. }
  36.  
  37. // Query using SelectMany()
  38. IEnumerable<string> resultSelectMany = employees.SelectMany(emp => emp.Skills);
  39.  
  40. Console.WriteLine("**************** SelectMany ******************");
  41.  
  42. // Only one foreach loop is required to iterate through the results
  43. // since query returns a one-dimensional collection.
  44. foreach (string skill in resultSelectMany)
  45. {
  46. Console.WriteLine(skill);
  47. }
  48.  
  49. Console.ReadKey();
  50. }
  51. }
  52.  
  53. /* Output
  54. **************** Select ******************
  55.  
  56. C
  57. C++
  58. Java
  59.  
  60. SQL Server
  61. C#
  62. ASP.NET
  63.  
  64. C#
  65. ASP.NET MVC
  66. Windows Azure
  67. SQL Server
  68.  
  69. **************** SelectMany ******************
  70.  
  71. C
  72. C++
  73. Java
  74. SQL Server
  75. C#
  76. ASP.NET
  77. C#
  78. ASP.NET MVC
  79. Windows Azure
  80. SQL Server
  81. */
What do you think?
I hope you will enjoy Select and SelectMany while programming with LINQ. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.