Skip to content

ErcanOPAK.com

  • ASP.Net WebForms
  • ASP.Net MVC
  • C#
  • SQL
  • MySQL
  • PHP
  • Devexpress
  • Reportviewer
  • About
C# / LINQ

What is the difference between Select and SelectMany in Linq

- 30.12.22 - ErcanOPAK

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.

enter image description here

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.

SelectMany in LINQ
If you want only the distinct program names and to retrieve the student name along with them then you should use that:
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:

Thanks for a such enlightening article.

Related posts:

Checking multiple contains on one string
Display HTPP Headers in C# & ASP.net
Converting a List to a comma separated string in C#
ASPxGridView - Disable CheckBox based on condition in GridViewCommandColumn
Post Views: 10

Post navigation

Differences between FirstOrDefault and SingleOrDefault in LINQ
What is the purpose of nameof in C#?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

September 2023
M T W T F S S
 123
45678910
11121314151617
18192021222324
252627282930  
« Aug    

Most Viewed Posts

  • Get the First and Last Word from a String or Sentence in SQL (665)
  • Get the User Name and Domain Name from an Email Address in SQL (657)
  • How to select distinct rows in a datatable in C# (508)
  • Add Constraint to SQL Table to ensure email contains @ (428)
  • Average of all values in a column that are not zero in SQL (347)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (328)
  • Find numbers with more than two decimal places in SQL (306)
  • Confirm before process with ASPxButton in Devexpress (304)
  • ASPxGridView – Disable CheckBox based on condition in GridViewCommandColumn (277)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (275)

Recent Posts

  • How to remove all non alphanumeric characters from a string in C#
  • How to get the Xth Day of the Week of the Year in C#
  • How to get formatted JSON in C#
  • How to convert JSON to XML or XML to JSON in C#
  • How to use OUTPUT for Insert, Update and Delete in SQL
  • How to get the first and last date of the current year in SQL
  • How to solve extra blank page at end of Microsoft Reportviewer
  • How to Use Picture-in-Picture in Chrome Browser
  • How to add some content to the right side of CardHeader on Bootstrap
  • How to change star rating color on mouseover/out, mouseenter/leave with Javascript

Most Viewed Posts

  • Get the First and Last Word from a String or Sentence in SQL (665)
  • Get the User Name and Domain Name from an Email Address in SQL (657)
  • How to select distinct rows in a datatable in C# (508)
  • Add Constraint to SQL Table to ensure email contains @ (428)
  • Average of all values in a column that are not zero in SQL (347)

Recent Posts

  • How to remove all non alphanumeric characters from a string in C#
  • How to get the Xth Day of the Week of the Year in C#
  • How to get formatted JSON in C#
  • How to convert JSON to XML or XML to JSON in C#
  • How to use OUTPUT for Insert, Update and Delete in SQL

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter

© 2023 ErcanOPAK.com

Proudly powered by WordPress | Theme: Xblog Plus by wpthemespace.com