我需要按键对字典进行排序,但是值是类项。
下面是类:
CLASS Person
PUBLIC PersonID
PUBLIC PersonName
PUBLIC GenderID
PUBLIC PersonAdditional
PRIVATE SUB class_initialize()
PersonID = null
PersonName = null
GenderID = null
PersonAdditional = null
END SUB
END CLASS
这是我的字典,填充了来自数组的数据:
Set dict = Server.CreateObject("Scripting.Dictionary")
FOR i = 0 TO UBOUND(arr_People)
key_person = arr_People(i).GenderID & arr_People(i).PersonName
dict.Add key_person, new Person
dict.Item(key_person).PersonName = arr_People(i).PersonName
dict.Item(key_person).GenderID = arr_People(i).GenderID
dict.Item(key_person).PersonID = arr_People(i).PersonID
dict.Item(key_person).PersonAdditional = arr_People(i).PersonAdditional
NEXT
我使用这个函数进行排序,但它似乎不起作用:
Function SortDictionary(objDict,intSort)
Dim strDict()
Dim objKey
Dim strKey,strItem
Dim X,Y,Z
Z = objDict.Count
If Z > 1 Then
ReDim strDict(Z,2)
X = 0
For Each objKey In objDict
strDict(X,dictKey) = CStr(objKey)
strDict(X,dictItem) = CStr(objDict(objKey))
X = X + 1
Next
For X = 0 to (Z - 2)
For Y = X to (Z - 1)
If StrComp(strDict(X,intSort),strDict(Y,intSort),vbTextCompare) > 0 Then
strKey = strDict(X,dictKey)
strItem = strDict(X,dictItem)
strDict(X,dictKey) = strDict(Y,dictKey)
strDict(X,dictItem) = strDict(Y,dictItem)
strDict(Y,dictKey) = strKey
strDict(Y,dictItem) = strItem
End If
Next
Next
objDict.RemoveAll
For X = 0 to (Z - 1)
objDict.Add strDict(X,dictKey), strDict(X,dictItem)
Next
End If
End Function
显示如下错误:
对象不支持此属性或方法
在这一行:
strDict(X,dictItem) = CStr(objDict(objKey)
我假设发生这种情况是因为字典中的值包含class而不仅仅是字符串或整数,但我不知道如何处理它。
你可以使用:
- 创建另一个仅包含字典键的数组
- 排序数组
- 通过遍历键数组读取字典值
代码如下:
Set dict = Server.CreateObject("Scripting.Dictionary")
Set arr_personKeys = CreateObject("System.Collections.ArrayList")
FOR i = 0 TO UBOUND(arr_People)
key_person = arr_People(i).GenderID & arr_People(i).PersonName
arr_personKeys.Add key_person
dict.Add key_person, new Person
dict.Item(key_person).PersonName = arr_People(i).PersonName
dict.Item(key_person).GenderID = arr_People(i).GenderID
dict.Item(key_person).PersonID = arr_People(i).PersonID
dict.Item(key_person).PersonAdditional = arr_People(i).PersonAdditional
NEXT
arrLength_personKeys = arr_personKeys.count - 2
SortArray arr_personKeys,arrLength_personKeys
下面是排序函数:
Function SortArray(arrayForSorting, arraySize)
for a = arraySize To 0 Step -1
for j = 0 to a
if arrayForSorting(j)>arrayForSorting(j+1) then
temp=arrayForSorting(j+1)
arrayForSorting(j+1)=arrayForSorting(j)
arrayForSorting(j)=temp
end if
next
next
End Function
现在您可以像这样遍历排序字典:
For i = 0 To arrLength_personKeys + 1
key = arr_personKeys(i)
Response.write dict(key).PersonID
Response.write dict(key).PersonName
Response.write dict(key).GenderID
Response.write dict(key).PersonAdditional
Next