C#

[C#]Dictionary 필터링하는 방법

DevStory 2022. 8. 29.

Dictonary 필터링하는 방법

Dictionary에서 특정 조건을 만족하는 데이터만 가져오고 싶은 상황이 존재할 수 있습니다.

 

이번 포스팅은 Dictionary의 키와 값을 필터링하는 몇 가지 방법을 소개합니다.


방법 1. LINQ의 Where 메서드 - 새로운 Dictionary 생성

첫 번째 방법으로 LINQ에서 제공하는 Where() 메서드를 사용하여 키 또는 값이 필터링된 새로운 Dictionary를 생성할 수 있습니다.

 

먼저, LINQ의 Where() 메서드를 사용하기 위해 다음 네임스페이스를 추가합니다.

using System.Linq;

배열 또는 컬렉션과 같은 데이터 집합을 필터링하는 Where() 메서드는 오버로드된 두 가지 버전이 존재합니다.

public static IEnumerable<TSource> Where<TSource>(
  this IEnumerable<TSource> source, 
  Func<TSource, bool> predicate);

public static IEnumerable<TSource> Where<TSource>(
  this IEnumerable<TSource> source, 
  Func<TSource, int, bool> predicate);

이번 포스팅은 Func<TSource, bool> predicate를 매개변수로 가지는 Where() 메서드를 사용할 것이며, Where() 메서드는 IEnumerable<TSource>를 반환합니다.

 

IEnumerable<TSource>를 Dictionary로 변환하기 위해 Where() 메서드 뒤에 ToDictionary() 메서드를 호출합니다.

 

LINQ에서 제공하는 Where() 메서드와 ToDictionary() 메서드에 대한 세부적인 내용은 아래 포스팅에서 확인할 수 있습니다.

 

[C#]LINQ 데이터 필터링 방법 - Where절

Where절 LINQ의 Where문은 원본 데이터에서 일부 조건을 만족하는 데이터를 추출해야하는 경우 사용됩니다. 예를 들자면, 아래 조건을 만족하는 데이터를 추출하기 위해 Where문을 사용할 수 있습니

developer-talk.tistory.com

 

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

ToDictionary 메서드 C#의 Dictionary 클래스는 Key-Value 쌍으로 구성된 컬렉션입니다. LINQ 결과는 IEnumerable 를 반환하므로 Key-Value 쌍으로 구성된 Dictionary으로 변환해야 하는 경우 특정 작업이 필요한..

developer-talk.tistory.com


예제 1. 값을 기준으로 필터링

다음 예제는 string 타입의 키와 int 타입의 값으로 구성된 Dictionary에서 값이 50 이상인 요소로 구성된 새로운 Dictionary를 생성합니다.

class Program
{
  static void Main(string[] args)
  {
    Dictionary<string, int> dict = new Dictionary<string, int>();
    dict.Add("React", 10);
    dict.Add("Java", 20);
    dict.Add("JavaScript", 30);
    dict.Add("TypeScript", 40);
    dict.Add("Oracle", 50);
    dict.Add("Kotlin", 60);
    dict.Add("C Sharp", 70);

    Dictionary<string, int> newDict = 
        dict.Where(item => item.Value >= 50)
            .ToDictionary(item => item.Key, item => item.Value);

    Console.WriteLine("[필터링 결과]");
    foreach (KeyValuePair<string, int> entry in newDict)
    {
      Console.WriteLine("Key: " + entry.Key + ", Value: " + entry.Value);
    }
  }
}

[실행 결과]

[필터링 결과]
Key: Oracle, Value: 50
Key: Kotlin, Value: 60
Key: C Sharp, Value: 70

예제 2. 키를 기준으로 필터링

다음 예제는 string 타입의 키와 int 타입의 값으로 구성된 Dictionary에서 키에 문자열 "Java"가 포함된 요소로 구성된 새로운 Dictionary를 생성합니다.

class Program
{
  static void Main(string[] args)
  {
    Dictionary<string, int> dict = new Dictionary<string, int>();
    dict.Add("React", 10);
    dict.Add("Java", 20);
    dict.Add("JavaScript", 30);
    dict.Add("TypeScript", 40);
    dict.Add("Oracle", 50);
    dict.Add("Kotlin", 60);
    dict.Add("C Sharp", 70);

    Dictionary<string, int> newDict = 
        dict.Where(item => item.Key.Contains("Java"))
            .ToDictionary(item => item.Key, item => item.Value);

    Console.WriteLine("[필터링 결과]");
    foreach (KeyValuePair<string, int> entry in newDict)
    {
      Console.WriteLine("Key: " + entry.Key + ", Value: " + entry.Value);
    }
  }
}

[실행 결과]

[필터링 결과]
Key: Java, Value: 20
Key: JavaScript, Value: 30

예제 3. 키와 값 둘 다 필터링

다음 예제는 string 타입의 키와 int 타입의 값으로 구성된 Dictionary에서 다음 두 가지 조건을 만족하는 요소로 구성된 새로운 Dictionary를 생성합니다.

 

조건 1. 키에 문자열 "Java"가 포함

조건 2. 값이 30 이상인 경우

class Program
{
  static void Main(string[] args)
  {
    Dictionary<string, int> dict = new Dictionary<string, int>();
    dict.Add("React", 10);
    dict.Add("Java", 20);
    dict.Add("JavaScript", 30);
    dict.Add("TypeScript", 40);
    dict.Add("Oracle", 50);
    dict.Add("Kotlin", 60);
    dict.Add("C Sharp", 70);

    Dictionary<string, int> newDict = 
        dict.Where(item => item.Key.Contains("Java") && item.Value >= 30)
            .ToDictionary(item => item.Key, item => item.Value);

    Console.WriteLine("[필터링 결과]");
    foreach (KeyValuePair<string, int> entry in newDict)
    {
      Console.WriteLine("Key: " + entry.Key + ", Value: " + entry.Value);
    }
  }
}

[실행 결과]

[필터링 결과]
Key: JavaScript, Value: 30

방법 2. 기존 Dictionary를 변경

두 번째 방법은 새로운 Dictionary를 생성하지 않고 기존 Dictionary를 변경하는 방법입니다.

 

[변경 방법]

순서 1. foreach문을 사용하여 Where() 메서드에서 반환된 결과를 List로 변환 후 순회합니다.

순서 2. 기존 Dictionary에서 Remove() 메서드를 호출합니다.

순서 3. Remove() 메서드의 매개변수로 Where() 메서드에서 반환된 결과의 키를 전달합니다.


예제 1. 값을 기준으로 필터링

다음 예제는 string 타입의 키와 int 타입의 값으로 구성된 Dictionary에서 값이 50 이상인 요소로 구성된 Dictionary로 변경합니다. 따라서, 값이 50 미만인 요소를 제거합니다.

class Program
{
  static void Main(string[] args)
  {
    Dictionary<string, int> dict = new Dictionary<string, int>();
    dict.Add("React", 10);
    dict.Add("Java", 20);
    dict.Add("JavaScript", 30);
    dict.Add("TypeScript", 40);
    dict.Add("Oracle", 50);
    dict.Add("Kotlin", 60);
    dict.Add("C Sharp", 70);

    Console.WriteLine("[삭제 전]");
    foreach (KeyValuePair<string, int> entry in dict)
    {
      Console.WriteLine("Key: " + entry.Key + ", Value: " + entry.Value);
    }

    foreach (var item in dict.Where(item => item.Value < 50).ToList())
    {
      dict.Remove(item.Key);
    }

    Console.WriteLine("\n[삭제 후]");
    foreach (KeyValuePair<string, int> entry in dict)
    {
      Console.WriteLine("Key: " + entry.Key + ", Value: " + entry.Value);
    }
  }
}

[실행 결과]

[삭제 전]
Key: React, Value: 10
Key: Java, Value: 20
Key: JavaScript, Value: 30
Key: TypeScript, Value: 40
Key: Oracle, Value: 50
Key: Kotlin, Value: 60
Key: C Sharp, Value: 70

[삭제 후]
Key: Oracle, Value: 50
Key: Kotlin, Value: 60
Key: C Sharp, Value: 70

예제 2. 키를 기준으로 필터링

다음 예제는 string 타입의 키와 int 타입의 값으로 구성된 Dictionary에서 키에 문자열 "Java"가 포함된 요소로 구성된 Dictionary로 변경합니다. 따라서, 키에 문자열 "Java"가 포함되지 않은 요소를 제거합니다.

class Program
{
  static void Main(string[] args)
  {
    Dictionary<string, int> dict = new Dictionary<string, int>();
    dict.Add("React", 10);
    dict.Add("Java", 20);
    dict.Add("JavaScript", 30);
    dict.Add("TypeScript", 40);
    dict.Add("Oracle", 50);
    dict.Add("Kotlin", 60);
    dict.Add("C Sharp", 70);

    Console.WriteLine("[삭제 전]");
    foreach (KeyValuePair<string, int> entry in dict)
    {
      Console.WriteLine("Key: " + entry.Key + ", Value: " + entry.Value);
    }

    foreach (var item in dict.Where(item => !item.Key.Contains("Java")).ToList())
    {
      dict.Remove(item.Key);
    }

    Console.WriteLine("\n[삭제 후]");
    foreach (KeyValuePair<string, int> entry in dict)
    {
      Console.WriteLine("Key: " + entry.Key + ", Value: " + entry.Value);
    }
  }
}

[실행 결과]

[삭제 전]
Key: React, Value: 10
Key: Java, Value: 20
Key: JavaScript, Value: 30
Key: TypeScript, Value: 40
Key: Oracle, Value: 50
Key: Kotlin, Value: 60
Key: C Sharp, Value: 70

[삭제 후]
Key: Java, Value: 20
Key: JavaScript, Value: 30
반응형

댓글