Sorting Dictionary of Strings and Numbers

前端 未结 3 1747
感情败类
感情败类 2021-01-24 18:01

I have a dictionary object that needs to be sorted, but the keys are date values in the form

[\'Apr. 2013\',\'May 2013\',\'Feb. 2013\',
\'Mar. 2013\',\'Jul. 2013\',\'         


        
3条回答
  •  [愿得一人]
    2021-01-24 18:54

    Code stolen from here:

      Const csSep = "|"
      Const cnMax = 100
    
      Dim sInp : sInp = "Apr. 2013|May. 2013|Apr. 2014|Feb. 2013|Apr. 2011|Mar. 2013|Jul. 2013|Aug. 2013"
      Dim aInp : aInp = Split(sInp, csSep) ' YourDic.Keys
      WScript.Echo "A:", vbCrLf & Join(aInp, vbCrLf)
      WScript.Echo "---------------------"
    
      Dim oNAL : Set oNAL = CreateObject( "System.Collections.ArrayList" )
      Dim oSB  : Set oSB  = CreateObject( "System.Text.StringBuilder" )
      Dim sWord
      For Each sWord In aInp
          Dim dtCmp : dtCmp = CDate(sWord) ' depends on regional/locale settings
          oSB.AppendFormat_3 "{0:yyyy-MM}{1}{2}", dtCmp, csSep, sWord
          sWord = oSB.ToString()
          oSB.Length = 0
          oNAL.Add sWord
      Next
      oNAL.Sort
    
      ReDim aOut(oNAL.Count - 1)
      Dim i
      For i = 0 To UBound(aOut)
          aOut(i) = Split(oNAL(i), csSep)(1)
      Next
      WScript.Echo "B:", vbCrLf & Join(aOut, vbCrLf)
    

    output:

    A:
    Apr. 2013
    May. 2013
    Apr. 2014
    Feb. 2013
    Apr. 2011
    Mar. 2013
    Jul. 2013
    Aug. 2013
    ---------------------
    B:
    Apr. 2011
    Feb. 2013
    Mar. 2013
    Apr. 2013
    May. 2013
    Jul. 2013
    Aug. 2013
    Apr. 2014
    

    The theory is (c) R. L. Schwartz (see Schwartzian transform).

    Update wrt Martha's answer (and my caveat):

    Don't have to much confidence in VBScript's date conversions:

    >> WScript.Echo CDate("Dez 2013")
    >>
    Error Number:       13  ' <-- can't read german
    Error Description:  Type mismatch
    
    >> WScript.Echo CDate("Dec 2013") ' <-- can read english
    >>
    01.12.2013 ' <-- can write german
    
    >> WScript.Echo DateValue("Dez 2013")
    >>
    Error Number:       13 ' <-- DateValue isn't more intelligent
    Error Description:  Type mismatch
    

提交回复
热议问题