2014-03-06 39 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 
相关问题