Difference between Select and SelectMany in LINQ


The difference between select and selectMany can be seen when we are accessing data from multilevel classes.

Download Sample Code – 2.62 Kb

In the below example we shall see what exactly is the difference while accessing the properties.

When we access some data by using select it gives us the data that is grouped under the parent (i.e gives multiple arrays). To access the output we need to loop twice.

////This code shows how to use Select()             
var Query2 = Builders.Select(Build => Build.Locations);

// Notice that two foreach loops are required to iterate through
// the results because the query returns a collection of arrays.            
foreach (List<String> BuildList in Query2)
{
        foreach (string builds in BuildList)
        {
                Console.WriteLine(builds);
        }

        Console.WriteLine();
}

But using the same sample when we use select many it gives the selected items in one array(i.e it give the output as it is joining all the output from select command)

// Query using SelectMany().            
var query1 = Builders.SelectMany(Build => Build.Locations);

// Only one foreach loop is required to iterate through the
// results because it is a one-dimensional collection.
// Select many joins the output of all the sub collections in to one.            
foreach (string Loc in query1)
        Console.WriteLine(Loc);

Output:

Difference select and selectMany
Difference Select and SelectMany

Happy learning 🙂

12 thoughts on “Difference between Select and SelectMany in LINQ

    • Hi,

      I have given a link for downloading the source code in the above post. There you will find full description of the difference.

      Thanks,
      Naveen Prabhu

      Like

  1. Can you post something related to persistent objects rather than in memory objects. I would like to see that. If at all the SelectMany merges the data, is it going to exclude the redundant ones?

    Like

    • Hi Santosh,

      Any object you read from will get queried in the memory, so I used Linq to objects samples. It can be extended with any other objects.

      Thanks,
      Codingsense

      Like

Leave a reply to Somnath Sonawne Cancel reply