VBS Scripting.Dictionary 排序

标签: , , , ,

在Scriptomatic中发现一个SortDictionary过程,可以对Scripting.Dictionary对象的元素进行排序。

'********************************************************************
'* SortDictionary
'* 
'* Shell sort based on:
'* http://support.microsoft.com/support/kb/articles/q246/0/67.asp
'********************************************************************
Sub SortDictionary(objDict, intSort)

   Const dictKey  = 1
   Const dictItem = 2

   Dim strDict()
   Dim objKey
   Dim strKey, strItem
   Dim intCount, i, j

   intCount = objDict.Count

   If intCount > 1 Then

      ReDim strDict(intCount, 2)

      i = 0
      For Each objKey In objDict
         strDict(i,dictKey)  = CStr(objKey)
         strDict(i,dictItem) = CStr(objDict(objKey))
         i = i + 1
      Next

      '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
      ' Perform a shell sort of the 2D string array
      '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
      For i = 0 To (intCount - 2)
         For j = i To (intCount - 1)
            If StrComp(strDict(i,intSort), strDict(j,intSort), vbTextCompare) > 0 Then
               strKey  = strDict(i,dictKey)
               strItem = strDict(i,dictItem)
               strDict(i,dictKey)  = strDict(j,dictKey)
               strDict(i,dictItem) = strDict(j,dictItem)
               strDict(j,dictKey)  = strKey
               strDict(j,dictItem) = strItem
            End If
         Next
      Next

      '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
      ' Erase the contents of the dictionary object
      '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
      objDict.RemoveAll

      '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
      ' Repopulate the dictionary with the sorted information
      '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
      For i = 0 To (intCount - 1)
         objDict.Add strDict(i,dictKey), strDict(i,dictItem)
      Next

   End If

End Sub

测试程序:

Dim oDic
Set oDic = CreateObject("scripting.dictionary")
oDic.Add "aaa", "demon"
oDic.Add "bbb", "blog"
oDic.Add "ccc", "http://demon.tw"

WScript.Echo "---- before sort ----"
For Each i In oDic
    WScript.Echo i, oDic(i)
Next

SortDictionary oDic, 2

WScript.Echo "---- after sort ----"
For Each i In oDic
    WScript.Echo i, oDic(i)
Next

如果排序的时候调用回调函数就更好了。

随机文章:

  1. 在VB中创建和使用VBS的内置WScript对象?
  2. VBS修改文件和文件夹的NTFS 权限
  3. iPad 2 完美越狱
  4. OpenWrt安装CIFS客户端挂载网络驱动器
  5. 64位系统VBS调用32位COM组件

留下回复