gpt4 book ai didi

sorting - 如何按对象属性vbscript对字典进行排序

转载 作者:行者123 更新时间:2023-12-01 12:16:08 26 4
gpt4 key购买 nike

我正在尝试使用一个函数对字典进行排序,该函数是我通过一个对象属性在网上找到的,该属性是 Id 但是在这个 For Each i In dict 行上,我收到了这条错误消息 Microsoft VBScript runtime错误:对象不支持此属性或方法。我已经尝试过 For Each i In dict.Items 但我得到与 'dict.Items' 相同的错误消息 我使用的是旧版本的 VBScript,因此它没有像 dict 这样的功能。计数

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

排序函数:

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

最佳答案

尝试将您的函数修改为:

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

排序前:

|Key             |Value                |
|----------------|---------------------|
|1 |1,Test1 |
|2 |2,Test2 |
|3 |3,Test3 |
|4 |4,Test4 |
|5 |5,Test5 |

排序后:

|Key             |Value                |
|----------------|---------------------|
|1 |5,Test5 |
|2 |4,Test4 |
|3 |3,Test3 |
|4 |2,Test2 |
|5 |1,Test1 |

我找不到更好的方法来交换值。我相信有更好的方法可以做到这一点。一旦我得到一些东西就会更新它。

关于sorting - 如何按对象属性vbscript对字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48114792/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com