[C# 문법] LINQ SelectMany 연산자

참조


SelectMany 연산자란?

  • SelectMany 연산자는 컬렉션 속성이 있는 일련의 객체가 았고 자식 컬렉션의 각 항목을 하나씩 열거해야 하는 경우에 사용하는 연산자입니다.
  • 쉽게 말해, Collection 안에 다른 Collection이 저장되어 있고, 이 중에서 Sub Collection의 데이터를 가져올 때 SelectManay 연산자를 이용합니다.

SelectMany 3가지 오버로드 내용

public static IEnumerable<TResult> SelectMany<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, IEnumerable<TResult>> selector);
public static IEnumerable<TResult> SelectMany<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, IEnumerable<TResult>> selector);
public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(this IEnumerable<TSource> source, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector);
  • SelectMany 연산자는 3가지 주요 오버로드가 있습니다.
    • 첫 번째 오버로드는 대상 객체의 컬렉션 속성을 선택하는 데 사용합니다.
    • 두 번째 오버로드는 대상 객체의 컬렉션 속성을 선택하는 데 사용되며 각 객체의 인덱스도 제공합니다. 예를 들어 시퀀스의 첫 번째 항목에 대해 인덱스 0을 제공하고 시퀀스의 두 번째 항목에 대해 인덱스 1을 제공합니다.
    • 세 번째 오버로드는 매우 유용한 기능을 제공ㅅ합니다. 위에 추가하여 익명 유형을 만들고 결과에 해당 익명 유형을 반환하는 데 사용할 수 있는 사용자 지정 함수도 제공합니다.

C# LINQ SelectManay 예제 코드

  • 직원 객체가 있고 직원 객체에는 Departments 라는 List Collection 이 있습니다.
using System;
using System.Collections.Generic;
using System.Linq;

namespace interfaceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Employee> employees = new()
            {
                new Employee
                {
                    ID = 1,
                    Name = "Kapil",
                    Departments = new List<Department>()
                    {
                        new Department { Name = "Marketing" },
                        new Department { Name = "Sales"}
                    }
                },
                new Employee
                {
                    ID = 2,
                    Name = "Raj",
                    Departments = new List<Department>()
                    {
                        new Department { Name = "Advertisement" },
                        new Department { Name = "Production"}
                    }
                },
                new Employee
                {
                    ID = 3,
                    Name = "Ramesh",
                    Departments = new List<Department>()
                    {
                        new Department { Name = "Production" },
                        new Department { Name = "Sales"}
                    }
                }
            };

            FirstOverridSelectManay(employees);
            SecondOverridSelectManay(employees);
            ThirdOverridSelectManay(employees);
        }

        public static void FirstOverridSelectManay(List<Employee> employees)
        {
            var result = employees.SelectMany(w => w.Departments);
            foreach (var dept in result)
            {
                Console.WriteLine(dept.Name);
            }

            Console.WriteLine();
        }

        public static void SecondOverridSelectManay(List<Employee> employees)
        {
            var result = employees.SelectMany((w, index) => w.Departments.Select(k => index.ToString() + "," + k.Name));
            foreach (var dept in result)
            {
                Console.WriteLine(dept);
            }

            Console.WriteLine();
        }

        public static void ThirdOverridSelectManay(List<Employee> employees)
        {
            var result = employees.SelectMany(w => w.Departments, (employee, department) => new { employee, department });
            foreach (var item in result)
            {
                Console.WriteLine(item.employee.Name + "," + item.department.Name);
            }

            Console.WriteLine();
        }

        public class Employee
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public List<Department> Departments { get; set; }
        }

        public class Department
        {
            public string Name { get; set; }
        }
    }
}

실행 결과

Marketing
Sales
Advertisement
Production
Production
Sales

0,Marketing
0,Sales
1,Advertisement
1,Production
2,Production
2,Sales

Kapil,Marketing
Kapil,Sales
Raj,Advertisement
Raj,Production
Ramesh,Production
Ramesh,Sales
728x90

이 글을 공유하기

댓글

Designed by JB FACTORY