The formal description for SelectMany() is:
Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence.
SelectMany() flattens the resulting sequences into one sequence and invokes a result selector function on each element.
The main difference is the result of each method while SelectMany() returns flattened results; Select() returns a list of lists instead of a flatter result set.
Therefore the result of SelectMany is a list in which you can iterate each item by just one foreach. But with the result of select you need an extra foreach loop to iterate through the results because the query returns a collection of arrays.
Let us create a class file with the name Student.cs and then copy and paste the following code.
using System.Collections.Generic; namespace LINQDemo { public class Student { public int ID { get; set; } public string Name { get; set; } public string Email { get; set; } public List<string> Programming { get; set; } public static List<Student> GetStudents() { return new List<Student>() { new Student(){ID = 1, Name = "James", Email = "James@j.com", Programming = new List<string>() { "C#", "Jave", "C++"} }, new Student(){ID = 2, Name = "Sam", Email = "Sara@j.com", Programming = new List<string>() { "WCF", "SQL Server", "C#" }}, new Student(){ID = 3, Name = "Patrik", Email = "Patrik@j.com", Programming = new List<string>() { "MVC", "Jave", "LINQ"} }, new Student(){ID = 4, Name = "Sara", Email = "Sara@j.com", Programming = new List<string>() { "ADO.NET", "C#", "LINQ" } } }; } } }
As you can see we have created the Student class with four properties. Please remember the Programming property returns list<string>. Here we also created one method which will return the List of students which will be going to act our data source.
We need to Projects all programming strings of all the students to a singleĀ IEnumerable<string>. As you can see, we have 4 students, so there will be 4 IEnumerable<string> sequences, which then we need to flattened to form a single sequence i.e. a single IEnumerable<string> sequence.