[C#] Dictionary sort by key, value example. 딕셔너리 정렬 방법 예제

Dictionary를 Key 또는 Value로 정리하는 방법입니다. 한 줄로 손쉽게 가능하답니다. 예제에서 딕셔너리에 "s"키를 먼저, "b"키를 나중에 넣었으나, 정렬의 결과로 "b"키가 먼저 오는 것을 확인할 수 있습니다.

딕셔너리 정렬하기 예제
Dictionary<string, string> dictionary = new Dictionary<string, string>();

dictionary.Add("s", "sang");
dictionary.Add("b", "beom");

dictionary = dictionary.OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value);
foreach (var v in dictionary)
{
    //key=b,value=beom
    //key=s,value=sang
    Debug.WriteLine($"key={v.Key},value={v.Value}");    
}

OrderBy(x => x.Key)를 통해 키 순서로 정렬하였는데, 밸류 순서로 정렬하려면 OrderBy(x => x.Value)로 하면 됩니다. ToDictionary에서는 키와 밸류를 그대로 보존하도록 하였는데 필요 시, Func<TSource, TKey>, Func<TSource, TElement> 메서드를 수정할 수 있습니다.

댓글