C#

[C#]Dictionary 값에 해당하는 키 가져오는 방법

DevStory 2022. 8. 20.

Dictonary 값에 해당하는 키 가져오는 방법

C#의 Dictionary는 <Key, Value> 형식의 데이터를 가지는 컬렉션입니다.

 

Dictionary의 키(Key)는 유니크하므로 중복될 수 없지만, 값(Value)은 중복될 수 있습니다.

 

따라서, Dictionary에는 특정 값을 만족하는 키가 여러 개 있을 수 있습니다.

 

이번 포스팅은 Dictionary에 특정 값을 만족하는 키를 가져오는 몇 가지 방법을 소개합니다.


방법 1. 반복문

가장 심플한 방법으로 반복문을 사용합니다.

 

먼저, 특정 값과 매핑되는 키가 여러 개 존재할 수 있으므로 키를 담을 수 있는 List 또는 배열을 선언합니다.

 

Dictionary를 순회하여 특정 값을 만족하는 경우 키를 List에 추가합니다.

 

다음 예제는 Dictionary에서 값이 10인 키를 List에 추가합니다.

class Program
{
  static void Main(string[] args)
  {
    Dictionary<string, int> dict = new Dictionary<string, int>()
    {
      {"둘리", 10 },
      {"또치", 10 },
      {"마이콜", 20 },
      {"고길동", 20 }
    };

    List<string> keyList = new List<string>();

    // Dictionary를 순회합니다.
    foreach(KeyValuePair<string, int> item in dict)
    {
      // Value가 10인 Key를 List에 추가합니다.
      if(item.Value == 10)
      {
        keyList.Add(item.Key);
      }
    }

    foreach(string key in keyList)
    {
      Console.Write(key + " ");
    }
  }
}

[실행 결과]

둘리 또치

다음 예제는 특정 값을 만족하는 Dictionary의 요소를 새로운 Dictionary에 추가합니다.

class Program
{
  static void Main(string[] args)
  {
    Dictionary<string, int> dict = new Dictionary<string, int>()
    {
      {"둘리", 10 },
      {"또치", 10 },
      {"마이콜", 20 },
      {"고길동", 20 }
    };

    Dictionary<string, int> newDict = new Dictionary<string, int>();

    // Dictionary를 순회합니다.
    foreach (KeyValuePair<string, int> item in dict)
    {
      // Value가 10인 Key와 Value를 새로운 Dictionary에 추가합니다.
      if(item.Value == 10)
      {
        newDict.Add(item.Key, item.Value);
      }
    }

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

[실행 결과]

Key: 둘리, Value: 10
Key: 또치, Value: 10

방법 2. LINQ의 Where, Select 메서드 

두 번째 방법으로 LINQ에서 제공하는 Where() 메서드를 사용합니다.

 

Where() 메서드는 배열 또는 컬렉션과 같은 데이터 집합을 필터링할 수 있습니다. 즉, 특정 조건을 만족하는 데이터를 추출합니다.

 

Select() 메서드는 특정 데이터만 가져옵니다. <Key, Value> 형식인 Dictionary에서 키만 가져올 수 있습니다.

 

먼저 LINQ에서 제공하는 기능을 사용하기 위해 다음 네임스페이스를 추가합니다.

using System.Linq;

다음 예제는 Dictionary에서 Where() 메서드를 사용하여 값이 10, 30인 키를 List에 추가합니다.

 

LINQ의 Select() 메서드는 IEnumerable<T>를 반환하므로 ToList() 메서드를 사용하여 List로 변환합니다.

class Program
{
  static void Main(string[] args)
  {
    Dictionary<string, int> dict = new Dictionary<string, int>()
    {
      {"둘리", 10 },
      {"또치", 10 },
      {"마이콜", 20 },
      {"고길동", 20 },
      {"도우넛", 30 }
    };

    List<string> keyList = dict
        .Where(item => item.Value == 10 || item.Value == 30)
        .Select(item => item.Key)
        .ToList();

    foreach (string key in keyList)
    {
      Console.Write(key + " ");
    }
  }
}

[실행 결과]

둘리 또치 도우넛

다음 예제는 특정 값을 만족하는 Dictionary의 요소를 새로운 Dictionary에 추가합니다.

 

Select() 메서드를 생략할 수 있으며, ToDictionary() 메서드를 사용하여 Dictionary로 변환합니다.

class Program
{
  static void Main(string[] args)
  {
    Dictionary<string, int> dict = new Dictionary<string, int>()
    {
      {"둘리", 10 },
      {"또치", 10 },
      {"마이콜", 20 },
      {"고길동", 20 },
      {"도우넛", 30 }
    };

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

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

[실행 결과]

Key: 둘리, Value: 10
Key: 또치, Value: 10
Key: 도우넛, Value: 30

방법 3. 특정 값을 만족하는 키가 한 개인 경우

Dictionary에서 값은 중복될 수 있습니다.

 

하지만, Dictionary에 등록되는 값이 유니크하다면 특정 값을 만족하는 키는 단 하나입니다.

 

LINQ에서 제공하는 FirsrtOrDefault() 메서드는 데이터 집합에서 특정 조건을 만족하는 첫 번째 위치의 데이터를 가져옵니다.

 

만약, 특정 조건을 만족하는 데이터가 없는 경우 FirstOrDefault() 메서드는 키의 타입에 해당하는 Default 값을 반환합니다.

 

다음 예제는 FirstOrDefault() 메서드를 사용하여 값이 30인 키를 가져옵니다.

class Program
{
  static void Main(string[] args)
  {
    Dictionary<string, int> dict = new Dictionary<string, int>()
    {
      {"둘리", 10 },
      {"또치", 10 },
      {"마이콜", 20 },
      {"고길동", 20 },
      {"도우넛", 30 }
    };

    string key = dict.FirstOrDefault(item => item.Value == 30).Key;

    Console.WriteLine("Key: " + key);
  }
}

[실행 결과]

Key: 도우넛
반응형

댓글