C#/LINQ

[C#]LINQ 결과를 Dictionary로 변환 - ToDictionary 메서드

DevStory 2022. 8. 15.

ToDictionary 메서드

C#의 Dictionary 클래스는 Key-Value 쌍으로 구성된 컬렉션입니다.

 

LINQ 결과는 IEnumerable<T>를 반환하므로 Key-Value 쌍으로 구성된 Dictionary으로 변환해야 하는 경우 특정 작업이 필요한데, LINQ에서 제공하는 ToDictionary() 메서드를 사용하여 LINQ 결과를 Dictionary으로 변환할 수 있습니다.

 

System.Linq의 Enumerable 클래스에 정의된 ToDictionary() 메서드는 네 가지 오버로드된 버전이 존재합니다.

public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(
  this IEnumerable<TSource> source, 
  Func<TSource, TKey> keySelector);

public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(
  this IEnumerable<TSource> source, 
  Func<TSource, TKey> keySelector, 
  IEqualityComparer<TKey> comparer);

public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(
  this IEnumerable<TSource> source, 
  Func<TSource, TKey> keySelector, 
  Func<TSource, TElement> elementSelector);

public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(
  this IEnumerable<TSource> source, 
  Func<TSource, TKey> keySelector, 
  Func<TSource, TElement> elementSelector, 
  IEqualityComparer<TKey> comparer);

이번 포스팅은 첫 번째 그리고 세 번째 ToDictionary() 메서드 사용 방법을 설명합니다.


예제 1. string 타입의 Key, int 타입의 Value

다음 예제는 Linq 결과를 string 타입의 Key, int 타입의 Value로 구성된 Dictionary로 변환합니다.

 

int 타입의 List에서 Where() 메서드를 사용하여 2보다 큰 요소를 추출합니다.

 

Where() 메서드에서 추출된 결과를 Dictionary로 변환하기 위해 ToDictionary() 메서드를 호출하고 Dictionary의 Key가 string 타입이므로 ToDicitonary() 메서드에서 int 타입을 string 타입으로 변환합니다.

class Program
{
  static void Main(string[] args)
  {
    List<int> intList = new List<int>()
    {
      1, 2, 3, 4, 5
    };

    Dictionary<string, int> linqToDictionary = intList
        .Where(num => num > 2)
        .ToDictionary(item => item.ToString());

    foreach (KeyValuePair<string, int> item in linqToDictionary)
    {
      Console.WriteLine("Key: " + item.Key + ", Value: " + item.Value);
    }
  }
}

[실행 결과]

Key: 3, Value: 3
Key: 4, Value: 4
Key: 5, Value: 5

예제 2. string 타입의 Key, int 타입의 Value에서 Value 값 변경

다음 예제는 Linq 결과를 string 타입의 Key, int 타입의 Value에 100을 곱한 결과를 Dictionary로 변환합니다.

 

int 타입의 List에서 Where() 메서드를 사용하여 2보다 큰 요소를 추출합니다.

 

ToDictonary() 메서드의 첫 번째 매개변수로 Key를 설정하는 람다식을 전달하고 두 번째 매개변수로 Value를 설정하는 람다식을 전달합니다.

class Program
{
  static void Main(string[] args)
  {
    List<int> intList = new List<int>()
    {
      1, 2, 3, 4, 5
    };

    Dictionary<string, int> linqToDictionary = intList
        .Where(num => num > 2)
        .ToDictionary(
            (item => item.ToString()),
            (item => item * 100));

    foreach (KeyValuePair<string, int> item in linqToDictionary)
    {
      Console.WriteLine("Key: " + item.Key + ", Value: " + item.Value);
    }
  }
}

[실행 결과]

Key: 3, Value: 300
Key: 4, Value: 400
Key: 5, Value: 500

예제 3. 사용자 정의 클래스

다음 예제는 사용자 정의 클래스인 Person 타입의 List에서 Where() 메서드를 사용하여 Age 프로퍼티가 25보다 큰 요소를 추출한 뒤 ID 프로퍼티를 Key로 설정합니다.

public class Person
{
  public int ID { get; set; }
  public string Name { get; set; }
  public int Age { get; set; }
}

class Program
{
  static void Main(string[] args)
  {
    List<Person> personList = new List<Person>()
    {
      new Person() {ID = 1000, Name = "둘리",   Age = 20},
      new Person() {ID = 2000, Name = "마이콜", Age = 30},
      new Person() {ID = 3000, Name = "고길동", Age = 40}
    };

    Dictionary<int, Person> linqToDictionary = personList
        .Where(person => person.Age > 25)
        .ToDictionary(person => person.ID);

    foreach (KeyValuePair<int, Person> item in linqToDictionary)
    {
      Console.WriteLine("Key: " + item.Key + 
          ", Value: { ID: " + item.Value.ID + 
          ", Name: " + item.Value.Name + 
          ", Age: " + item.Value.Age + " }");
    }
  }
}

[실행 결과]

Key: 2000, Value: { ID: 2000, Name: 마이콜, Age: 30 }
Key: 3000, Value: { ID: 3000, Name: 고길동, Age: 40 }
반응형

댓글