Difference between Select and SelectMany in LINQ
Posted by codingsense on September 16, 2008
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:
Happy learning

Ben y said
Very helpful.
Yuriy Zaletskyy said
Hello.
I would like to see also what is Build.Locations
codingsense said
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
Mahindrakar said
Thannks Buddy
Daniel said
Thanks mate.
Asad said
Great help
John said
Very simple and elegant explanation. Thank you.
Santosh Kumar Arisetty said
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?
codingsense said
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
Somnath Sonawne said
Very good example
learnerplates (@learnerplts) said
The is the best example I’ve seen, thanks for the sample code too.