2008-10-01 5 views
6

C'est une question assez simple: comment trier une collection?Tri d'une collection dans ASP classique

J'ai un fichier CSV avec des lignes dans un ordre aléatoire. Je voudrais trier les lignes en fonction de la date dans une colonne. Est-ce que j'ajoute les lignes à un jeu d'enregistrements? Puis-je trier avec un Scripting.Dictionary?

J'ai clairement été gâté avec .NET et Linq, et maintenant je me retrouve au pays du classique ASP, réalisant que je devais le savoir il y a 7 ans, et qui manquait énormément de génériques. Je me sens comme un n00b complet.

Répondre

14

Dans ce cas, j'obtenir de l'aide du grand frère .net. Il est possible d'utiliser System.Collections.Sortedlist dans votre application ASP et de trier vos paires de valeurs-clés.

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 

BTW si les classes .net suivantes sont aussi disponibles:

  • System.Collections.Queue
  • System.Collections.Stack
  • System.Collections.ArrayList
  • système. Collections.SortedList
  • System.Collections.Hashtable
  • System.IO.StringWriter
  • System.IO.MemoryStream;

Voir aussi: Marvels of COM .NET interop

+0

Génie! Fonctionne un régal – harriyott

+0

FYI, la liste est automatiquement triée par des clés et il n'est pas possible de trier la liste par des valeurs. –

0

Cela fait longtemps pour moi aussi. IIRC vous n'avez pas une option hors de la boîte.

Si j'étais vous, je mettrais toutes les données dans un tableau, puis trier le tableau. J'ai trouvé une implémentation QuickSort ici: http://www.4guysfromrolla.com/webtech/012799-3.shtml

+0

complètement hors-sujet, mais j'avais cette même icône comme userpic dans mon livejournal. :) – Wayne

+0

Je l'ai eu quelque part hors de l'Internet, donc j'ai pensé qu'il y a une très forte possibilité que quelqu'un d'autre l'utilise aussi :) – rslite

3

je partirais avec l'approche RecordSet. Utilisez le pilote de texte. Vous devrez changer le répertoire dans la chaîne de connexion et le nom de fichier dans l'instruction select. La propriété étendue "HDR = Yes" spécifie qu'il y a une ligne d'en-tête dans le fichier CSV que je suggère car cela rendra l'écriture du script SQL plus facile.

<% 

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

J'aurais dû y penser ... un jeu sur la mémoire.Merci –

0

Une réponse tardive à la fin, mais encore de la valeur.

Je travaillais avec de petites collections, donc je pouvais me permettre l'approche où j'insérais l'article au bon endroit à chaque fois, reconstruisant efficacement la collection sur chaque addition.

La classe VBScript est la suivante:

'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

Excuses, le code ressemble un peu à la cack lorsque la syntaxe est en surbrillance. –

+1

vous pouvez utiliser [conseils de langue] (http://meta.stackexchange.com/questions/981/syntax-highlighting-language-hints) (plus précisément, 'lang-vb') pour que la surbrillance fonctionne correctement. –