2014-02-23 5 views
0

정렬 된 사전에 대한 정보가 있습니다.사전을 정렬했습니다.

나는 그들에 대해 읽은 것부터 그들 안에있는 핵심 가치에 따라 스스로를 분류합니다. 그 맞습니까? 또한, 사전은 값이 읽혀질 때 자동으로 자체 정렬을 수행합니까?

그렇다면 사전을 변경하여 키와 관련된 값을 통해 사전을 정렬 할 수있는 방법이 있습니까? 예를 들어, 나는 다음과 정렬 된 사전을 가지고 :

Key: 1 Value: 290 
Key: 4 Value: 40 
Key: 86 Value: 7 

을하지만 다음 작업을 수행 할 수 있도록 제가하고 싶은 것은 :

Key: 4 Value: 40 
Key: 1 Value: 290 
Key: 86 Value: 7 

정렬 된 사전과 같이 그것을 분류 할

Key: 86 Value: 7 
Key: 4 Value: 40 
Key: 1 Value: 290 

마지막으로이 정렬의 첫 번째 및 두 번째 지점에 액세스하여 다른 항목에 할당 할 수있는 방법은 무엇입니까?

+3

가능한 중복 값?] (http://stackoverflow.com/questions/289/how-do-you-sort-a-dictionary-by-value) – dcastro

+1

.NET Framework에는이 작업이 자동으로 수행되는 컬렉션이 없습니다. 사전을 정렬해야 할 때마다 정렬해야합니다. [여기] (http://stackoverflow.com/questions/289/how-do-you-sort-a-dictionary-by-value) . – dcastro

답변

0

기본적으로 SortedDictionary<TKey, TValue>Key을 기반으로 Sorting을 수행하지만 Value은 수행하지 않습니다. MSDN에서

: 당신이 Value에 따라 정렬을 갖고 싶어

하지만 당신은 LINQ OrderBy() 방법 asbelow을 사용할 수 있습니다 SortedDictionary

은에 분류되어 키/값 쌍의 컬렉션을 나타냅니다 열쇠.

이 시도 :

var SortedByValueDict = dict.OrderBy(item => item.Value); 

전체 코드 :

class Program 
{ 
static void Main(string[] args) 
{ 
    SortedDictionary<int, int> dict = new SortedDictionary<int, int>(); 
    dict.Add(4, 40); 
    dict.Add(1, 290); 
    dict.Add(86, 7); 

    Console.WriteLine("Sorted Dictionary Items sorted by Key"); 
    foreach (var v in dict) 
    { 
    Console.WriteLine("Key = {0} and Value = {1}", v.Key, v.Value); 
    } 

    Console.WriteLine("------------------------\n"); 
    Console.WriteLine("Sorted Dictionary Items sorted by Value"); 
    var SortedByValueDict = dict.OrderBy(item => item.Value); 

    foreach (var v in SortedByValueDict) 
    { 
    Console.WriteLine("Key = {0} and Value = {1}", v.Key, v.Value); 
    } 
} 
} 

출력 :

Sorted Dictionary Items sorted by Key 
Key = 1 and Value = 290 
Key = 4 and Value = 40 
Key = 86 and Value = 7 
------------------------ 

Sorted Dictionary Items sorted by Value 
Key = 86 and Value = 7 
Key = 4 and Value = 40 
Key = 1 and Value = 290 
당신이에 의해 사전으로 정렬하려면 어떻게해야 [의