VBScript: Sorting Items from Scripting.Dictionary

末鹿安然 提交于 2019-12-10 23:28:35

问题


I have the code below... it grabs data like this:

name1, name4, name2, name3

and list like this ([ ] is a checkbox):

[ ] name 1 [ ] name 4 [ ] name 2 [ ] name 3

<%
    Set DicionarioMyData = CreateObject("Scripting.Dictionary")
    Set MyData= TarefasConexaoMSSQL.Execute("SELECT A FROM TABLE")
    If Not MyData.EOF Then

        Do While Not MyData.EOF
            ItensDoMyData = MyData("A")

            If Not IsNull(ItensDoMyData) Then
                ItensSeparadosDoMyData = Split(ItensDoMyData, ",")

                For i = 0 To UBound(ItensSeparadosDoMyData)
                    ItensDoMyData = Trim(ItensSeparadosDoMyData(i))

                    If Not DicionarioMyData.Exists(ItensDoMyData) Then
                        DicionarioMyData.Add ItensDoMyData, i
                        %>
                  <input name="itens" type="checkbox" value="<% Response.Write ItensDoMyData %>"><label><% Response.Write ItensDoMyData %></label>
                        <%
                    End If
                Next
            End If
         MyData.MoveNext
    End If
%>

It's working, but i am not able to sort it, so the right output should be:

[ ] name 1 [ ] name 2 [ ] name 3 [ ] name 4

Is it possible to sort this kinda of output?


回答1:


VBScript doesn't offer good sorting options however on anything remotely modern you will have access to the COM Visible classes provided by .NET, one of which is the System.Collections.SortedList class.

Hence your code can look something more like this

Dim sl : Set sl = CreateObject("System.Collections.SortedList")

Dim rs : Set rs = conn.Execute("SELECT SomeField FROM SomeTable") 

If Not rs.EOF Then 

    Do While Not rs.EOF  
        If Not IsNull(rs("SomeField")) Then  
            AddStringListToSortedList rs("SomeField"), sl
        End If
    Loop

End If

rs.Close

For i = 0 To sl.Count - 1
    WriteCheckBox sl.GetKey(i)
Next

Sub AddStringListToSortedList(stringList, sortedList)

    Dim arr: arr = Split(stringList, ",")
    Dim i, item
    For i = 0 To UBound(arr)
        item = Trim(arr(i))
        If item <> "" Then
            If Not sortedList.Contains(item) Then
                sortedList.Add item, i
            End If
        End If
    Next

End Sub

Function WriteCheckbox(value)
%>
<input name="itens" type="checkbox" value="<%=Server.HTMLEncode(value)%>" /><label><%=Server.HTMLEncode(value) %></label>
<%
End Function  


来源:https://stackoverflow.com/questions/11317541/vbscript-sorting-items-from-scripting-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!