Back to: LINQ Tutorial For Beginners and Professionals
LINQ SelectMany Method in C# with Examples
In this article, I am going to discuss the LINQ SelectMany Projection Method in C# with Examples. Please read our previous article where we discussed the LINQ Select Projection Operator in C# with Examples. The Linq SelectMany Method belongs to the projection Category Operator. As part of this article, we are going to discuss the following pointers in detail.
- What is Linq SelectMany Method?
- Examples using both LINQ Query and Method Syntax to Understand SelectMany Method.
What is Linq SelectMany Method?
The SelectMany Method in LINQ is used to project each element of a sequence or collection or data source to an IEnumerable<T> type and then flatten the resulting sequences into one sequence. That means the SelectMany Projection Method combines the records from a sequence of results and then converts it into one result. If this is not clear at the moment, then don’t worry we will understand this with Examples.
Example to Understand LINQ SelectMany Projection Method using C#:
Let us understand the LINQ SelectMany Method with an example using C#. In the below example, we are using the SelectMany Method to flatten the resulting sequences into one sequence. Here, you can see that the SelectMany method returns an IEnumerable<char>. This is because the SelectMany method returns all the elements from the sequence. Here the nameList is the sequence or collection or the data source. And the sequence contains two strings. And we know the string is a collection of characters. So, the SelectMany method fetches all the characters from the above two strings and then converts them into one sequence i.e. IEnumerable<char>. In the below example, we are using LINQ Method Syntax i.e. using the LINQ SelectMany Method.
using System; using System.Collections.Generic; using System.Linq; namespace LINQDemo { class Program { static void Main(string[] args) { List<string> nameList =new List<string>(){"Pranaya", "Kumar" }; IEnumerable<char> methodSyntax = nameList.SelectMany(x => x); foreach(char c in methodSyntax) { Console.Write(c + " "); } Console.ReadKey(); } } }
So, when we execute the above program, it will give us the following output. Basically, it will combine all the characters of both strings and form the result as a collection of characters which is shown in the below output.
LINQ SelectMany Using Query Syntax in C#:
The most important point that you need to remember is there is no such SelectMany Operator available in LINQ to write Query Syntax. But we can achieve this by writing multiple “from clauses” in the query as shown in the below example. In the below example, we are fetching all the strings from the nameList collection to str object and then we are using another from clause to fetch all the characters from the str object and then we are projecting the characters which are going to contain all the characters available in both strings.
using System; using System.Collections.Generic; using System.Linq; namespace LINQDemo { class Program { static void Main(string[] args) { List<string> nameList =new List<string>(){"Pranaya", "Kumar" }; IEnumerable<char> querySyntax = from str in nameList from ch in str select ch; foreach (char c in querySyntax) { Console.Write(c + " "); } Console.ReadKey(); } } }
Now, execute the above example code and you will see the same output as the LINQ Method Syntax as shown in the below image.
Example to Understand LINQ SelectMany Projection Method with Complex Data Type in C#
Let us create a class file with the name Student.cs and then copy and paste the following code into it. As you can see, we have created the following Student class with four properties. Further, if you notice the Programming property of the Student class returns List<string>. Here we have also created one method which will return the List of students which will be going to act as our data source.
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" } } }; } } }
Now, our requirement is to Project 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. And, we need to flatten to form a single sequence i.e. a single IEnumerable<string> sequence.
The complete example code is given below. In the below example, I am showing both LINQ Query Syntax and Method Syntax to achieve the same.
using System; using System.Collections.Generic; using System.Linq; namespace LINQDemo { class Program { static void Main(string[] args) { //Using Method Syntax List<string> MethodSyntax = Student.GetStudents().SelectMany(std => std.Programming).ToList(); //Using Query Syntax IEnumerable<string> QuerySyntax = from std in Student.GetStudents() from program in std.Programming select program; //Printing the values foreach (string program in MethodSyntax) { Console.WriteLine(program); } Console.ReadKey(); } } }
When we execute the program, it will give us the following output. Here, you can see, it contains all the programming strings from all the students. Also, if you notice it is also containing the same string multiple times.
Example to Understand how to Remove Duplicates while using LINQ SelectMany Method:
If you notice, in our previous example, we get the output as expected but with duplicate program names. If you want only the distinct program names then you need to apply the distinct method on the result set which is shown in the below examples. The LINQ Distinct Method is going to return distinct elements from a sequence by using the default equality comparer to compare values. In our upcoming articles, we will discuss Comparer and the Distinct Method in detail. For now, just remember distinct method is going to return distinct elements from a sequence.
using System; using System.Collections.Generic; using System.Linq; namespace LINQDemo { class Program { static void Main(string[] args) { //Using Method Syntax List<string> MethodSyntax = Student.GetStudents() .SelectMany(std => std.Programming) .Distinct() .ToList(); //Using Query Syntax IEnumerable<string> QuerySyntax = (from std in Student.GetStudents() from program in std.Programming select program).Distinct().ToList(); //Printing the values foreach (string program in QuerySyntax) { Console.WriteLine(program); } Console.ReadKey(); } } }
With the above changes in place, now run the application code and you will see that it will remove the duplicate program names and will show the distinct program names from the sequence as shown in the below image.
Complex Example to Understand LINQ SelectMany Method using C#:
Now, let us proceed and see more complex examples to understand the LINQ SelectMany Method. Our requirement is to retrieve the student’s name along with the program language names. The following example exactly does the same. For this, we are going to use the other overloaded version of the SelectMany method. In the below example, I am showing both Query and Method Syntax to achieve the same.
using System; using System.Collections.Generic; using System.Linq; namespace LINQDemo { class Program { static void Main(string[] args) { //Using Method Syntax var MethodSyntax = Student.GetStudents() .SelectMany(std => std.Programming, (student, program) => new { StudentName = student.Name, ProgramName = program } ) .ToList(); //Using Query Syntax var QuerySyntax = (from std in Student.GetStudents() from program in std.Programming select new { StudentName = std.Name, ProgramName = program }).ToList(); //Printing the values foreach (var item in QuerySyntax) { Console.WriteLine(item.StudentName + " => " + item.ProgramName); } Console.ReadKey(); } } }
Output:
In the next article, I am going to discuss Where Filtering Method in LINQ with Examples. I hope this article gives you a very good understanding of how to use the LINQ SelectMany Method in C# with Examples.