C#

[C#]Dictionary 정렬 방법

DevStory 2021. 12. 20.

이번 포스팅에서는 Dictionary 객체를 키(Key), 값(Value)으로 정렬하는 방법을 소개합니다.

 

 첫 번째 방법

Dirctionary 인스턴스의 Keys 속성에 확장 메서드인 ToList()를 사용하여 List 객체를 생성합니다. List 객체의 Sort() 함수를 사용하여 Key를 정렬하고 새로운 Dictionary를 반환하는 방법이 있습니다.

내림차순으로 정렬하고 싶다면, Sort() 함수 호출 후 Reverse() 함수를 호출합니다.

class Program
{
    public static Dictionary<string, int> SortDictionary(Dictionary<string, int> dict)
    {
        // Key 정렬 후 반환되는 Dictionary 객체
        Dictionary<string, int> sortDict = new Dictionary<string, int>();

        // Key 목록을 List로 변환
        List<string> list = dict.Keys.ToList();

        // list 정렬
        list.Sort();

        // 내림차순으로 정렬하고 싶다면 Sort() 함수 호출 후 reverse() 함수를 호출
        //list.Reverse();

        // 정렬된 Dictionary 객체 구현
        foreach (var key in list)
        {
            sortDict.Add(key, dict[key]);
        }

        return sortDict;
    }

    static void Main(string[] args)
    {
        Dictionary<string, int> dict = new Dictionary<string, int>();
        dict.Add("AB", 20);
        dict.Add("C", 50);
        dict.Add("DE", 10);
        dict.Add("BCD", 90);
        dict.Add("BCDE", 5);

        Dictionary<string, int> sortDict = SortDictionary(dict);

        foreach (KeyValuePair<string, int> item in sortDict)
        {
            Console.WriteLine("정렬된 순서 Key : {0} , Value : {1}", item.Key, item.Value);
        }
    }
}

실행 결과

위 방법으로는 Dictionary 객체의 Key만 정렬할 수 있습니다.


▶ 두 번째 방법

간단한 방법으로 Dictionary에 내장된 OrderBy() 함수를 사용합니다. 내림차순으로 정렬하고 싶은 경우 OrderByDescending() 함수를 사용합니다.

Dictionary 타입으로 반환해야 하므로 ToDictionary() 함수를 OrderBy() 또는 OrderByDescending() 뒤에 연결합니다. 

public static Dictionary<string, int> SortDictionary(Dictionary<string, int> dict)
{
    // 내림차순인 경우 OrderByDescending() 함수로 변경
    return dict.OrderBy(item => item.Key).ToDictionary(x => x.Key, x => x.Value);
}

실행 결과는 첫 번째 방법과 동일하며, 제가 구현한 SortDictionary() 함수의 내부만 변경되었습니다. 정렬 기준이 Key가 아닌 Value라면, item.Keyitem.Value로 변경합니다.


 세 번째 방법

세 번째 방법으로 Linq를 사용하는 방법입니다. Linq는 .net 3.5부터 지원하므로 이하 버전에서는 동작하지 않습니다.

Linq에서 지원하는 방법으로 Dictionary 객체를 정렬 후 ToDictionary() 함수로 Dictionary 타입으로 변환합니다.

public static Dictionary<string, int> SortDictionary(Dictionary<string, int> dict)
{
    // 내림차순은 ascending을 descending으로 변경
    var sortVar = from item in dict
                  orderby item.Key descending
                  select item;

    return sortVar.ToDictionary(x => x.Key, x => x.Value);
}

실행 결과는 동일하며, 정렬 기준이 Key가 아닌 Value라면, item.Keyitem.Value로 변경합니다.

 

이상으로 Dirctionary 객체를 정렬하는 세 가지 방법을 소개하였으며 위 예제에서 사용된 SortDictionary() 함수를 제네릭 함수로 구현한다면, 더 좋은 코드가 될 거라 생각합니다.

 

반응형

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

[C#]const와 readonly 차이점  (1) 2021.12.25
[C#]First, FirstOfDefault 함수 사용 방법  (0) 2021.12.20
[C#]Dictionary value 값으로 key 찾기  (0) 2021.12.20
[C#]Dictionary 사용 방법  (2) 2021.12.19
[C#]List 속성별로 정렬  (1) 2021.10.03

댓글