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", "https://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. Ubuntu从NTP服务器同步时间
  2. 人人网状态及评论导出工具
  3. 批处理技术内幕:Unicode
  4. VBS中TextStream对象的ReadLine方法
  5. 在WordPress中使用jQuery库

留下回复