Dev*_*Dev 3 sorting vbscript dictionary
我正在尝试使用我在网上找到的对象属性(即 Id)函数对字典进行排序,但在这一行For Each i In dict我收到此错误消息 Microsoft VBScript 运行时错误:对象不支持此属性或方法。我已经尝试过,For Each i In dict.Items但我收到与“dict.Items”相同的错误消息我使用的是旧版本的 VBScript,因此它不具有以下功能dict.Count
VBScript 类:
Class TestClass
Public ID
Public TestText
Private Sub Class_Initialize
TestText = ""
End Sub
End Class
Set gDic = CreateObject("Scripting.Dictionary")
For i = 1 to 5
Set temp = new TestClass
temp.ID = i
temp.TestText = "Test" & i
gDic.Add i,temp
Next
Set NewDic = SortDict(gDic)
msgbox NewDic.Items()(1).TestText
Run Code Online (Sandbox Code Playgroud)
排序功能:
Function SortDict(ByVal dict)
Dim i, j, temp
For Each i In dict
For Each j In dict
If(dict.Item(i) <= dict.Item(j)) Then
temp = dict.Item(i)
dict.Item(i) = dict.Item(j)
dict.Item(j) = temp
End If
Next
Next
Set SortDict = dict
End Function
Run Code Online (Sandbox Code Playgroud)
尝试将您的函数修改为:
Function SortDict(dict)
Dim i, j, arrKeys, arrItems
arrKeys = dict.keys 'Array containing the keys
arrItems = dict.Items 'Array containing the Items(which are nothing but objects of class TestClass)
Set tempObj = New TestClass
For i=0 To UBound(arrItems)-1 'From 1st element to the penultimate element
For j=i+1 To UBound(arrItems) 'From i+1th element to last element
If arrItems(i).id < arrItems(j).id Then 'Sorting in DESCENDING ORDER by the Property "ID"
tempObj.ID = arrItems(i).ID
tempObj.TestText = arrItems(i).testText
dict.item(arrKeys(i)).ID = arrItems(j).ID
dict.item(arrKeys(i)).TestText = arrItems(j).TestText
dict.item(arrKeys(j)).ID = tempObj.ID
dict.item(arrKeys(j)).TestText = tempObj.TestText
End If
Next
Next
Set SortDict = dict
End Function
Run Code Online (Sandbox Code Playgroud)
排序前:
|Key |Value |
|----------------|---------------------|
|1 |1,Test1 |
|2 |2,Test2 |
|3 |3,Test3 |
|4 |4,Test4 |
|5 |5,Test5 |
Run Code Online (Sandbox Code Playgroud)
排序后:
|Key |Value |
|----------------|---------------------|
|1 |5,Test5 |
|2 |4,Test4 |
|3 |3,Test3 |
|4 |2,Test2 |
|5 |1,Test1 |
Run Code Online (Sandbox Code Playgroud)
我找不到更好的方法来交换值。我确信有更好的方法可以做到这一点。一旦我得到东西就会更新它。
| 归档时间: |
|
| 查看次数: |
6781 次 |
| 最近记录: |