2012-09-26 34 views
1

我知道SortedDictionary在WP7中不可用...所以必須自己排序。WP7 SortedDictionary

我已經找到了一些例子,我目前使用此代碼

Dictionary<string, TimetableClass> AllClasses = new Dictionary<string, TimetableClass>() 
     { 
      { "Maths", new TimetableClass {ClassName="Maths", Location="RM1"}}, 
      { "Physics", new TimetableClass {ClassName="Physics", Location="PM1"}}, 
      { "English", new TimetableClass {ClassName="English", Location="PM1"}}, 
      { "Algebra", new TimetableClass {ClassName="Algebra", Location="A1"}} 

     }; 

     var sortedDict = new Dictionary<string, TimetableClass>(); 

     foreach (KeyValuePair<string, TimetableClass> singleclass in AllClasses.OrderBy(key => key.Value)) 
     { 
      sortedDict.Add(singleclass.Key, singleclass.Value); 
     } 

但是當我運行此我上的foreach例外嗎?

異常是未處理的參數異常 - 「價值確實在預期的範圍內,機器人降」

真的不知道我做了什麼錯在這裏。 任何幫助表示讚賞。

  • 感謝
+0

你的代碼沒有意義。您無法對字典進行排序,只要將值添加到新字典中,訂單就會丟失。您可能想要將值添加到List >中。 –

回答

1

這應該工作

foreach (KeyValuePair<string, TimetableClass> singleclass in AllClasses.OrderBy(item => item.Key)) 
     { 
      sortedDict.Add(singleclass.Key, singleclass.Value); 
     } 

另外,如果你想基於對象(值)進行排序,試試這個

foreach (KeyValuePair<string, TimetableClass> singleclass in AllClasses.OrderBy(item => item.Value.ClassName)) 
     { 
      sortedDict.Add(singleclass.Key, singleclass.Value); 
     } 

最後,你也可以利用這個而不是foreach循環,並且不需要額外的「sortedDict」字典。

AllClasses = AllClasses.OrderBy(item => item.Key).ToDictionary(item => item.Key, item => item.Value); 
+0

是的,這工作正常 - 謝謝!只要看看差異,我現在意識到,我試圖按對象(值)排序,而不是按照您的代碼排序。大概是這個問題,因爲對象不能被'命令'? – Peter

+0

是的!或者,如果您想基於對象(值)進行排序,請嘗試此AllClasses.OrderBy(item => item.Value.ClassName)' – nkchandra

+0

檢查更新的答案:) – nkchandra