[英]How to sort the keys of a dictionary in reverse order using VB.NET?
我有一本字典:
Dim dicItems As Dictionary(of Integer, String)
字典中的项目是:
1,cat
2,dog
3,bird
我希望订单是:
3,bird
2,dog
1,cat
您无法对字典进行排序,而您需要的是排序列表。
Dim dicItems As New SortedList(Of Integer, String)
这将按键值对项目进行排序。 如果你想像你的例子那样按降序输出项目,你总是可以从列表的末尾开始循环,然后移到开头。
以下链接提供了有关SortedList的更多信息。
http://msdn.microsoft.com/en-us/library/ms132319%28v=vs.110%29.aspx
您可以使用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)
字典没有您可以依赖的隐式顺序(“返回项目的顺序未定义”)。
作为Shadows的附加组件,谁建议使用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
不知道为什么你会这么想,因为字典中的项目顺序通常无关紧要,但你可以这样做:
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
作为主题的变体,您可以将dicItems.Reverse()
替换为其他LINQ替代方案,例如OrderBy
,因此您可以Key
, Value
或其组合进行排序。 例如,这个dicItems.OrderBy(Function(x) x.Value)
给出了输出:
3,bird
1,cat
2,dog
(按值按字母顺序排序,按升序排序)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.