C#

[C#]Dictionary value 값으로 key 찾기

DevStory 2021. 12. 20.

Dictionary 클래스는 <Key, Value> 형식의 컬렉션으로 Key는 Dictionary 객체의 고유한 값이며, Value는 Key와 매핑되는 값입니다.

 

이번 포스팅은 Dictionary 객체에서 Value로 Key가 존재하는지 체크하는 방법들을 소개합니다.

 


Enumerable.FirstOrDefault() 함수를 사용

첫 번째 방법으로 FirstOrDefault() 함수를 사용하여 지정된 Value와 일치하는 Dictionary의 첫 번째 항목을 반환합니다.

 

다음은 Value가 20인 Key가 존재하는지 FirstOrDefault() 함수로 체크하는 예제입니다.

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

public static class Extensions
{
    public static K FindFirstKeyByValue<K, V>(this Dictionary<K, V> dict, V val)
    {
        return dict.FirstOrDefault(entry =>
            EqualityComparer<V>.Default.Equals(entry.Value, val)).Key;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> EmployeeList = new Dictionary<string, int>(1);

        EmployeeList.Add("홍길동", 30);
        EmployeeList.Add("또치", 20);
        EmployeeList.Add("마이콜", 20);
        EmployeeList.Add("희동이", 3);

        int findValue = 20;

        string key = EmployeeList.FindFirstKeyByValue(findValue);

        if (key != null)
        {
            Console.WriteLine("Key \"{0}\"의 Value는 \"{1}\"", key, findValue);
        }
        else
        {
            Console.WriteLine("Value \"{0}\"을(를) 가지는 Key를 찾지 못했습니다.", findValue);
        }
    }
}

 


foreach문 사용

두 번째 방법으로 foreach문을 사용하여 Dictionary 객체의 요소를 접근하여 지정된 Value와 일치하는 항목이 있는지 체크합니다.

 

다음은 지정된 Value와 일치하는 첫 번째 항목만 반환합니다.

using System;
using System.Collections.Generic;

public static class Extensions
{
    public static K FindFirstKeyByValue<K, V>(this Dictionary<K, V> dict, V val)
    {
        foreach (KeyValuePair<K, V> pair in dict)
        {
            if (EqualityComparer<V>.Default.Equals(pair.Value, value))
            {
                return pair.Key;
            }
        }
        return default;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> EmployeeList = new Dictionary<string, int>(1);

        EmployeeList.Add("홍길동", 30);
        EmployeeList.Add("또치", 20);
        EmployeeList.Add("마이콜", 20);
        EmployeeList.Add("희동이", 3);

        int findValue = 20;

        string key = EmployeeList.FindFirstKeyByValue(findValue);

        if (key != null)
        {
            Console.WriteLine("Key \"{0}\"의 Value는 \"{1}\"", key, findValue);
        }
        else
        {
            Console.WriteLine("Value \"{0}\"을(를) 가지는 Key를 찾지 못했습니다.", findValue);
        }
    }
}

 

다음은 지정된 Value와 일치하는 항목을 ArrayList로 반환합니다.

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

public static class Extensions
{
    public static ArrayList FindFirstKeyByValue<K, V>(this Dictionary<K, V> dict, V val)
    {
        ArrayList keyList = new ArrayList();
        
        foreach (KeyValuePair<K, V> pair in dict)
        {
            if (EqualityComparer<V>.Default.Equals(pair.Value, value))
            {
                keyList.Add(pair.Key);
            }
        }
        return keyList;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> EmployeeList = new Dictionary<string, int>(1);

        EmployeeList.Add("홍길동", 30);
        EmployeeList.Add("또치", 20);
        EmployeeList.Add("마이콜", 20);
        EmployeeList.Add("희동이", 3);

        int findValue = 20;

        ArrayList keyList = EmployeeList.FindFirstKeyByValue(findValue);

        if (keyList.Count > 0)
        {
            foreach(string key in keyList)
            {
                Console.WriteLine("Key \"{0}\"의 Value는 \"{1}\"", key, findValue);
            }
        }
        else
        {
            Console.WriteLine("Value \"{0}\"을(를) 가지는 Key를 찾지 못했습니다.", findValue);
        }
    }
}

Inverse Dictionary

세 번째 방법으로 Inverse Dictionary를 만드는 방법입니다. Dictionary 객체의 모든 Value가 고유한 경우 Key가 되고 Key가 Value가 되는 Inverse Dictionary를 만들 수 있습니다.

 

단점으로는 Dictionary 객체에서 Value의 값이 하나라도 중복되는 경우 ArgumentException이 발생합니다.

 

다음은 Inverse Dictionary를 만들어서 지정된 value와 일치하는 항목이 있는지 체크하는 예제입니다.

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

public static class Extensions
{
    public static K FindFirstKeyByValue<K, V>(this Dictionary<K, V> dict, V val)
    {
        Dictionary<V, K> revDict = dict.ToDictionary(pair => pair.Value, pair => pair.Key);
        return revDict[val];
    }
}

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> EmployeeList = new Dictionary<string, int>(1);

        EmployeeList.Add("홍길동", 30);
        EmployeeList.Add("또치", 20);
        EmployeeList.Add("마이콜", 25);
        EmployeeList.Add("희동이", 3);

        int findValue = 25;

        string key = EmployeeList.FindFirstKeyByValue(findValue);

        if (key != null)
        {
            Console.WriteLine("Key \"{0}\"의 Value는 \"{1}\"", key, findValue);
        }
        else
        {
            Console.WriteLine("Value \"{0}\"을(를) 가지는 Key를 찾지 못했습니다.", findValue);
        }
    }
}

 

반응형

'C#' 카테고리의 다른 글

[C#]First, FirstOfDefault 함수 사용 방법  (0) 2021.12.20
[C#]Dictionary 정렬 방법  (0) 2021.12.20
[C#]Dictionary 사용 방법  (2) 2021.12.19
[C#]List 속성별로 정렬  (1) 2021.10.03
[C#]List 거꾸로 뒤집기(Reverse)  (0) 2021.10.03

댓글