Difference between Select and SelectMany in LINQ

Difference between Select and SelectMany in LINQ

29 Mar 2024
Intermediate
46.4K Views
6 min read
Learn via Video Course & by Doing Hands-on Labs

ASP.NET MVC with WebAPI Course

Select Vs Select-Many in LINQ: An Overview

In this LINQ Tutorial, you will learn SELECT and SELECT-MANY Operators in LINQ and select and select many Operators with some actual Programming Examples.

Select and Select-Many, both are projection operators, which means, they select values from the list, collection, or other sources. A select operator is used to select values from a collection while a Select-Many operator is used to select values from a collection of collections i.e. nested collection. Select operator produces one result value for every source value while SelectMany produces a single result that contains a concatenated value for every source value. And SelectMany operator flattens IEnumerable<IEnumerable<T>> to IEnumrable<T> i.e. list of list to list.

You can understand Select and SelectMany Operator in LINQ more clearly when you see the actual programming examples.

SELECT OPERATOR EXAMPLE:

using System;
using System.Collections.Generic;
using System.Linq;
 
namespace OperatorTutorial
{
    class SoftwareCompany
    {
        public string employeeName { get; set; }
        public int employeeSalary { get; set; }
        public List employeeDetails { get; set; }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            var result = from p in GetCompanyDetails()
                         select new { p.employeeName, p.employeeSalary, p.employeeDetails };
            foreach (var r in result)
            {
                Console.WriteLine(r);
            }
            Console.ReadKey();
        }
 
        //Creating List of employee
        static List GetCompanyDetails()
        {
            List employee = new List
            {
            new SoftwareCompany
                {
               employeeName = "Vishnu",
               employeeSalary = 20000,
               employeeDetails = new List{"Software developer","Pune","Maharashtra"}
                },
            new SoftwareCompany
                {
               employeeName = "Priya",
               employeeSalary = 40000,
               employeeDetails = new List{"QA","Mumbai","Maharashtra"}
                },
            new SoftwareCompany
                {
               employeeName = "Jagat",
               employeeSalary = 800000,
               employeeDetails = new List{"Manager","Banglore","Karnataka "}
                },
            };
            return employee;
        }
    }
}

Output:

{ employeeName = Vishnu, employeeSalary = 20000, employeeDetails = System.Collections.Generic.List`1[System.String] }
{ employeeName = Priya, employeeSalary = 40000, employeeDetails = System.Collections.Generic.List`1[System.String] }
{ employeeName = Jagat, employeeSalary = 800000, employeeDetails = System.Collections.Generic.List`1[System.String] }

Explanation:

If you read the output carefully, you will notice that the "employeeDetails" is not displayed correctly. At the place of "employeeDetails", the program displays the "System.Collections.Generic.List" message. This is just because employeeDetails is a nested list and to overcome this problem to display the field properly, we need to implement SelectMany Operator.

SELECT MANY OPERATOR EXAMPLE:

using System;
using System.Collections.Generic;
using System.Linq;
 
namespace OperatorTutorial
{
    class SoftwareCompany
    {
        public string employeeName { get; set; }
        public int employeeSalary { get; set; }
        public List employeeDetails { get; set; }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            var result = from p in GetCompanyDetails()
                         select new { p.employeeName, p.employeeSalary, p.employeeDetails };;
                         
            foreach (var r in result.SelectMany(SoftwareCompany => SoftwareCompany.employeeDetails))
            {
                Console.WriteLine(r);
            }
            Console.ReadKey();
        }
 
        //Creating List of employee
        static List GetCompanyDetails()
        {
            List employee = new List
            {
            new SoftwareCompany
                {
               employeeName = "Vishnu",
               employeeSalary = 20000,
               employeeDetails = new List{"Software developer","Pune","Maharashtra"}
                },
            new SoftwareCompany
                {
               employeeName = "Priya",
               employeeSalary = 40000,
               employeeDetails = new List{"QA","Mumbai","Maharashtra"}
                },
            new SoftwareCompany
                {
               employeeName = "Jagat",
               employeeSalary = 800000,
               employeeDetails = new List{"Manager","Banglore","Karnataka "}
                },
            };
            return employee;
        }
    }
}

Output:

Output:

Software developer
Pune
Maharashtra
QA
Mumbai
Maharashtra
Manager
Banglore
Karnataka 

Explanation:

In the above example, We have used Select Many Operator to print nested list values. So according to it, select-many operator is useful when working with collections of collections (e.g., lists of lists or arrays of arrays) or when you want to transform and combine elements from multiple sources into a single sequence.
Summary:

I hope you will enjoy Select and SelectMany while programming with LINQ. I would like to have feedback from my blog readers. Your valuable feedback, questions, or comments about this article are always welcome. Read more articles related to LINQ. Enjoy coding...!

FAQs

Q1. When to use SelectMany?

when you want to work with collections of collections or when you need to flatten and project data from nested structures

Q2. What is the use of FirstOrDefault in LINQ?

The use of FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>, TSource) Returns the first element of the sequence that satisfies a condition, or a specified default value if no such element is found.

Q3. How to select multiple properties in LINQ?

To select multiple values from a list using LINQ, we can use the Select method. This method allows you to project each element of a sequence into a new form.
Share Article
Batches Schedule
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this