按数字键对字典排序 [英] Sort Dictionary by Numerical Key
本文介绍了按数字键对字典排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含整数键和整数项的字典,只需要根据该键对字典进行排序,但是我发现的所有示例仅适用于字符串键.
I have a dictionary with integer keys and integer items, and just need to sort the dictionary based on the key, but all examples I've found work only for string keys.
推荐答案
已编辑以添加解决方案以输出X和Y数组
edited to add a solution to output X and Y arrays
您可以使用SortedList
对象并构建如下的帮助子:
you could use SortedList
object and build a helper sub like follows:
Sub SortDictionary(dict As Object)
Dim i As Long
Dim key As Variant
With CreateObject("System.Collections.SortedList")
For Each key In dict
.Add key, dict(key)
Next
dict.RemoveAll
For i = 0 To .Keys.Count - 1
dict.Add .GetKey(i), .Item(.GetKey(i))
Next
End With
End Sub
将被如下利用:
SortDictionary dict '<--| give 'SortDictionary()' sub a dictionary object to sort by its keys
例如,这是一个测试:
Sub main()
Dim dict As Object
Dim key As Variant
Set dict = CreateObject("Scripting.Dictionary")
With dict
.Add 5, 15
.Add 4, 14
.Add 3, 13
.Add 2, 12
.Add 1, 11
End With
SortDictionary dict
With dict
For Each key In .Keys
Debug.Print key, .Item(key)
Next
End With
End Sub
可以很容易地扭曲上面的内容,以从字典keys
和items
中返回X
和Y
数组,如下所示:
what above can be easily twicked to return X
and Y
arrays out of dictionary keys
and items
, as follows:
Sub SortDictionaryToArray(dict As Object, XArray As Variant, YArray As Variant)
Dim i As Long
Dim key As Variant
With CreateObject("System.Collections.SortedList")
For Each key In dict
.Add key, dict(key)
Next
ReDim XArray(0 To .Count)
ReDim YArray(0 To .Count)
For i = 0 To .Keys.Count - 1
XArray(i) = .GetKey(i)
YArray(i) = .Item(.GetKey(i))
Next
End With
End Sub
将在您的主要子站点中被利用,如下所示:
to be exploited in your main sub as follows:
SortDictionaryToArray dict, Xs, Ys
如您在此完整测试中所见:
as you can see in this complete test:
Sub main()
Dim dict As Object
Dim i As Long
Dim Xs As Variant, Ys As Variant
Set dict = CreateObject("Scripting.Dictionary")
With dict
.Add 5, 15
.Add 4, 14
.Add 3, 13
.Add 2, 12
.Add 1, 11
End With
SortDictionaryToArray dict, Xs, Ys
For i = 0 To UBound(Xs)
Debug.Print Xs(i), Ys(i)
Next
End Sub
这篇关于按数字键对字典排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文