C# - Example of SelectMany() Method in LINQ

Learn about the SelectMany() method in Linq and its C# implementation. By Nidhi Last updated : April 01, 2023

Here we will create to demonstrate the SelectMany() method of Linq, here we will get the skills of employees and print on the console screen.

C# program to demonstrate the example of SelectMany() method in LINQ

The source code to demonstrate the SelectMany() method of Linq is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to demonstrate the 
//SelectMany() method in Linq.

using System;
using System.Collections.Generic;
using System.Linq;

public class Employee {
  public int ID;
  public string Name;
  public List < string > Skills;

  public static List < Employee > GetEmpDetails() {
    return new List < Employee > () {
      new Employee() {
          ID = 101, Name = "Amit", Skills = new List < string > () {
            "C",
            "C++",
            "DS"
          }
        },
        new Employee() {
          ID = 102, Name = "Sumit", Skills = new List < string > () {
            "C#",
            "VB"
          }
        },
        new Employee() {
          ID = 103, Name = "Patriq", Skills = new List < string > () {
            "JAVA",
            "JSP",
            "Servlet"
          }
        },
        new Employee() {
          ID = 104, Name = "Arun", Skills = new List < string > () {
            "ADO.NET",
            "OLEDB",
            "ODBC"
          }
        }
    };
  }

  static void Main(string[] args) {
    List < string > skill_list = Employee.GetEmpDetails().SelectMany(emp => emp.Skills).ToList();

    foreach(string skill in skill_list) {
      Console.Write(skill + " ");
    }
    Console.WriteLine();
  }
}

Output

C C++ DS C# VB JAVA JSP Servlet ADO.NET OLEDB ODBC
Press any key to continue . . .

Explanation

In the above program, we created an Employee that contains three data members ID, Name, and Skills. Here we created two static methods GetEmpDetails() and Main()

In the GetEmpDetails() method, we created multiple objects of Employee class with a list of employees and return them.

List<string> skill_list = Employee.GetEmpDetails().SelectMany(emp => emp.Skills).ToList();

Using the above code we find the skills of all employees and then converted them into collection List.

foreach (string skill in skill_list)
{
    Console.Write(skill+" ");
}

In the above code, we printed the all skills of all employees on the console screen.

C# LINQ Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.