2014-03-06 40 views
2

我有一本字典:如何使用VB.NET以相反的順序對字典的鍵進行排序?

Dim dicItems As Dictionary(of Integer, String) 

在字典中的項目有:

1,cat 
2,dog 
3,bird 

我想爲了:

3,bird 
2,dog 
1,cat 
+2

一個字典裏沒有隱含爲了你可以依靠。 –

+0

@TimSchmelter:這是不正確的。字典中的項目按照添加的順序存儲。雖然命令沒有關係或者不應該因爲任何實際的原因... – Neolisk

+1

@Neilisk:閱讀[docs](http://msdn.microsoft.com/en-us/library/xfhwa508。aspx):_「項目返回的順序未定義」_它是您不能依賴的實現細節,最初的順序與插入順序相同。實際上,只要字典被修改,訂單就會改變。更好的話(J. Skeet):http://stackoverflow.com/a/6384765/284240 –

回答

2

您可以使用LINQ輕鬆地解決這個問題:如果你想

Dim dicItems As New Dictionary(Of Integer, String) 
With dicItems 
    .Add(1, "cat") 
    .Add(2, "dog") 
    .Add(3, "bird") 
End With 

dim query = from item in dicItems 
      order by item.Key descending 
      select item 

,你也可以使用Lambda語法:

Dim query = dicItems.OrderByDescending(Function(item) item.Key) 
+0

謝謝我試圖在我的字典中使用擴展.OrderByDescending方法,但我不確定要傳遞什麼參數。 dicItems.OrderByDescending。你在這裏有工作雖然 – user2221178

+0

你應該可以做'dicItems.OrderByDescending(function(item)item.Key)' –

+0

我試過dicItems.OrderByDescending(Function(item)item.Key),但似乎沒有逆轉順序。 – user2221178

3

無法排序字典,你需要的是一個排序列表。

Dim dicItems As New SortedList(Of Integer, String) 

這將按鍵值排序項目。如果您希望按照您的示例降序排列項目,則可以始終從列表末尾開始循環,然後移至開頭。

下面的鏈接有更多關於SortedList的信息。

http://msdn.microsoft.com/en-us/library/ms132319%28v=vs.110%29.aspx

+0

你也可以使用帶'IComparer(Of Int32)'的構造函數,並提供一個降序排序的構造函數。 –

0

不知道爲什麼你會想,既然在詞典項目的順序通常並不重要,但你可以做這樣的:

Dim dicItems As New Dictionary(Of Integer, String) 
With dicItems 
    .Add("1", "cat") 
    .Add("2", "dog") 
    .Add("3", "bird") 
End With 

Dim dicItemsReversed As New List(Of KeyValuePair(Of Integer, String)) 
dicItemsReversed.AddRange(dicItems.Reverse()) 

請注意,我輸出到在這種情況下是不同的集合,即Generic.List。如果要替換原來的內容,然後你可以這樣做:

dicItems.Clear() 
For Each kv In dicItemsReversed 
    dicItems.Add(kv.Key, kv.Value) 
Next 

由於關於這一主題的變化,您可以與其他LINQ的替代品代替dicItems.Reverse(),如OrderBy,這樣你就可以,例如,排序通過Key,Value或其組合。例如,這dicItems.OrderBy(Function(x) x.Value)給出的輸出:

3,bird  
1,cat 
2,dog 

(按字母順序排序的值,升序)

2

字典中沒有隱含o您可以信賴的訂單(「退貨項目的順序未定義」)。

作爲附加的陰影回答誰建議使用構造使用SortedList你可以得到降序排列,其採用IComparer(Of Int32)

Dim list = New SortedList(Of Integer, String)(New DescendingComparer()) 
list.Add(3, "bird") 
list.Add(1, "cat") 
list.Add(2, "dog") 

Public Class DescendingComparer 
    Implements IComparer(Of Int32) 

    Public Function Compare(x As Integer, y As Integer) As Integer Implements System.Collections.Generic.IComparer(Of Integer).Compare 
     Return y.CompareTo(x) 
    End Function 
End Class 
相關問題