Different Between SelectMany And Select In LINQ

In this article, we are going to learn what is the difference between Select and SelectMany.

What is select?

A Select operator is used to select values from the collection.

What is SelectMany?

A SelectMany operator is used to select values from the collection of collection.

The Select operator returns one result value for every source value, while SelectMany returns a single result that contains a concatenated value for every source value. Actually, SelectMany operator flatten IEnumerable<IEnumerable<T>> to IEnumerable<T>.

Let us understand with the help of an example.

using System;
using System.Linq;
using System.Collections.Generic;

          
public class Employee
{
 public string Name { get; set; }
 public List<string> Language { get; set; }
}

public class Program
{
 public static void Main(string[] args)
 {
   List<Employee> employees = new List<Employee>();
   Employee emp1 = new Employee { Name = "Hafeezjaha", Language = new List<string> { "Node", ".Net Core", "C++" } };
   Employee emp2 = new Employee { Name = "Jaha", Language = new List<string> { "SQL Server", "C#", "ASP.NET" } };
   Employee emp3 = new Employee { Name = "Shaikh", Language = new List<string> { "C#", "ASP.NET MVC", "Angular", "SQL Server" } };

   employees.Add(emp1);
   employees.Add(emp2);
   employees.Add(emp3);

   // Query using Select()
   IEnumerable<List<String>> resultSelect = employees.Select(e=> e.Language);

   Console.WriteLine("=========Select==========");

   // Two foreach loops are required to iterate through the results
   // because the query returns a collection of arrays.
   foreach (List<String> languageList in resultSelect)
   {
    // Console.WriteLine(skillList);
     foreach (string language in languageList)
     {
       Console.WriteLine(language);
     }
     Console.WriteLine();
   }

   // Query using SelectMany()
  IEnumerable<string> resultSelectMany = employees.SelectMany(emp => emp.Language);
 	
 	Console.WriteLine("============ SelectMany ============");

   // Only one foreach loop is required to iterate through the results 
   // since query returns a one-dimensional collection.
   foreach (string language in resultSelectMany)
   {
    Console.WriteLine(language);
   }
  }
}

In the above example, you can see that while using Select you have to use a two loop to get LanguageList data but with the help of SelectMany, you get the same data using a single loop.

OutPut

=========Select==========
Node
.Net Core
C++

SQL Server
C#
ASP.NET

C#
ASP.NET MVC
Angular
SQL Server

============ SelectMany ============
Node
.Net Core
C++
SQL Server
C#
ASP.NET
C#
ASP.NET MVC
Angular
SQL Server

That’s it.

Also check, Custom Authorization In .NET Core 5.0

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories