Pages

Sunday, February 24, 2013

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);