2008-10-01 27 views
6

Es una pregunta bastante simple: ¿cómo puedo ordenar una colección?Ordenar una colección en ASP clásico

Tengo un archivo CSV con filas en orden aleatorio. Me gustaría ordenar las filas según la fecha en una columna. ¿Agrego las filas a un juego de registros? ¿Puedo ordenar con un Scripting.Dictionary?

claramente he sido mimado con .NET y Linq, y ahora me encuentro de nuevo en la tierra del asp clásico, dándome cuenta de que debo haberlo sabido hace 7 años, y faltando genéricos inmensamente. Me siento como un n00b completo.

Respuesta

14

En este caso me gustaría obtener la ayuda del hermano mayor .net. Es posible usar System.Collections.Sortedlist dentro de su aplicación ASP y obtener sus pares de valores clave ordenados.

set list = server.createObject("System.Collections.Sortedlist") 
with list 
    .add "something", "YY" 
    .add "something else", "XX" 
end with 

for i = 0 to list.count - 1 
    response.write(list.getKey(i) & " = " & list.getByIndex(i)) 
next 

Por cierto, si las siguientes clases .NET están disponibles también:

  • System.Collections.Queue
  • System.Collections.Stack
  • System.Collections.ArrayList
  • sistema. Collections.SortedList
  • System.Collections.Hashtable
  • System.IO.StringWriter
  • System.IO.MemoryStream;

Véase también: Marvels of COM .NET interop

+0

Genius! Funciona como un regalo – harriyott

+0

FYI, la lista se ordena automáticamente por claves y no es posible ordenar la lista por valores. –

0

Ha pasado mucho tiempo para mí también. IIRC no tiene una opción lista para usar.

Si fuera usted pondría todos los datos en una matriz y luego ordenaría la matriz. Encontré una implementación de QuickSort aquí: http://www.4guysfromrolla.com/webtech/012799-3.shtml

+0

Completamente offtopic, pero no tenía el mismo icono como hace Userpic en mi livejournal. :) – Wayne

+0

Lo conseguí en algún lugar fuera de Internet, así que pensé que hay una gran posibilidad de que alguien más lo esté usando también :) – rslite

3

me gustaría ir con el enfoque de registros. Usa el controlador de texto. Tendrá que cambiar el directorio en la cadena de conexión y el nombre de archivo en la instrucción de selección. la propiedad extendida "HDR = Yes" especifica que hay una fila de encabezado en el CSV que sugiero, ya que hará que escribir el psuedo SQL sea más fácil.

<% 

Dim strConnection, conn, rs, strSQL 

strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\inetpub\wwwroot\;Extended Properties='text;HDR=Yes;FMT=Delimited';" 

Set conn = Server.CreateObject("ADODB.Connection") 
conn.Open strConnection 

Set rs = Server.CreateObject("ADODB.recordset") 
strSQL = "SELECT * FROM test.csv order by date desc" 
rs.open strSQL, conn, 3,3 

WHILE NOT rs.EOF 
    Response.Write(rs("date") & "<br/>") 
    rs.MoveNext 
WEND 

rs.Close 
Set rs = Nothing 

conn.Close 
Set conn = Nothing 

%> 
+0

Debería haber pensado en eso ... un juego de memoria.Gracias –

0

A finales de respuesta tarde para esto, pero todavía de valor.

Estaba trabajando con colecciones pequeñas, así que podía permitirme el enfoque donde insertaba el elemento en el lugar correcto en cada ocasión, reconstruyendo de manera efectiva la colección en cada adición.

clase El VBScript es el siguiente:

'Simple collection manager class. 
'Performs the opration of adding/setting a collection item. 
'Encapulated off here in order to delegate responsibility away from the collection class. 
Class clsCollectionManager 
    Public Sub PopulateCollectionItem(collection, strKey, Value) 
     If collection.Exists(strKey) Then 
      If (VarType(Value) = vbObject) Then 
       Set collection.Item(strKey) = Value 
      Else 
       collection.Item(strKey) = Value 
      End If 
     Else 
      Call collection.Add(strKey, Value) 
     End If 
    End Sub 

    'take a collection and a new element as input parameters, an spit out a brand new collection 
    'with the new item iserted into the correct location by order 
    'This works on the assumption that the collection it is receiving is already ordered 
    '(which it should be if we always use this method to populate the item) 

    'This mutates the passed collection, so we highlight this by marking it as byref 
    '(this is not strictly necessary as objects are passed by reference anyway) 
    Public Sub AddCollectionItemInOrder(byref existingCollection, strNewKey, Value) 
     Dim orderedCollection: Set orderedCollection = Server.CreateObject("Scripting.Dictionary") 
     Dim strExistingKey 

     'If there is something already in our recordset then we need to add it in order. 

     'There is no sorting available for a collection (or an array) in VBScript. Therefore we have to do it ourself. 
     'First, iterate over eveything in our current collection. We have to assume that it is itself sorted. 
     For Each strExistingKey In existingCollection 

      'if the new item doesn't exist AND it occurs after the current item, then add the new item in now 
      '(before adding in the current item.) 
      If (Not orderedCollection.Exists(strNewKey)) And (strExistingKey > strNewKey) Then 
       Call PopulateCollectionItem(orderedCollection, strNewKey, Value) 
      End If 
      Call PopulateCollectionItem(orderedCollection, strExistingKey, existingCollection.item(strExistingKey)) 
     Next 

     'Finally check to see if it still doesn't exist. 
     'It won't if the last place for it is at the very end, or the original collection was empty 
     If (Not orderedCollection.Exists(strNewKey)) Then 
      Call PopulateCollectionItem(orderedCollection, strNewKey, Value) 
     End If 

     Set existingCollection = orderedCollection 
    End Sub 
End Class 
+0

Disculpas, el código parece un poco extraño cuando se resalta la sintaxis. –

+1

puede usar [consejos sobre el idioma] (http://meta.stackexchange.com/questions/981/syntax-highlighting-language-hints) (específicamente, 'lang-vb') para que el resaltado funcione correctamente. –