2011-01-30 7 views
1

WP7はSortedDictionaryをサポートしていないので、そのキーで辞書をソートする必要があります。どのように私はそれをすてきで、簡単で、最適にすることができますか?辞書でキーをソートする?

+0

[キーに関して場所に辞書のソート]の可能な重複(http://stackoverflow.com/questions/2705607/sorting-a-dictionary-in-place-with-respect -to-keys) – nawfal

答えて

0

私はこのコードを試してみました:

Dictionary<string, string> dict = new Dictionary<string,string>(); 
dict.Add("3", "three"); 
dict.Add("1", "one"); 
dict.Add("2", "two"); 

var sortedDict = (from entry in dict orderby entry.Key ascending select entry); 

foreach (var k in sortedDict) 
{ 
    Console.WriteLine("key:{0}, val={1} ", k.Key, k.Value); 
} 

これは動作しますが、sortedDictは辞書ではありません。私はそれを解決:

sortedDict = (from entry in dict orderby entry.Key ascending select entry) 
      .ToDictionary(x => x.Key, x => x.Value); 
+0

これを解決しました:dict =(dict orderbyエントリのエントリから.Key昇順選択エントリ).ToDictionary(x => x.Key、x => x.Value); – Cyan

1

このスタックオーバーフローの問題には、LINQを使用するソリューションが含まれています。

How do you sort a dictionary by value?

+0

私はこのコードを試しました: 辞書 dict = new Dictionary (); dict.Add( "3"、 "three"); dict.Add( "1"、 "one"); dict.Add( "2"、 "two"); var sortedDict =(dict orderbyエントリのエントリから.Key昇順選択エントリ); これは機能しますが、sortedDictは辞書ではありません。どうすれば辞書にすることができますか? も試しました dict.OrderBy(x => x.Key); これは機能しません。どうして? – Cyan

+0

解決済み: dict =(dict orderbyエントリのエントリから.Key昇順選択エントリ).ToDictionary(x => x.Key、x => x.Value); – Cyan

関連する問題