Satyajit
Satyajit

Reputation: 141

how to sort the Dates in array list in vb.net?

i have several files named in dated format(dd/mm/yyyy) .i have to collect them and sort in arraylist ? any suggestion ...i did like this

Dim filepath As String = FileStr
Dim directoryPath As String = System.IO.Path.GetDirectoryName(filepath)
Dim arrayList As New System.Collections.ArrayList()
For Each file As String In System.IO.Directory.GetFiles(directoryPath)
 arrayList.Add(System.IO.Path.GetFileNameWithoutExtension(file))
Next
arrayList.Sort()

Upvotes: 0

Views: 2527

Answers (1)

User999999
User999999

Reputation: 2520

NOTE: a file named 29/06/2015.txt is not valid on Windows. the following code has been tested using the following formats: yyyy-mm-dd,yyyy-dd-mm,...

Would the following implentation not work? This uses a List however instead of your arraylist.

Dim filepath As String = FileStr
Dim directoryPath As String = System.IO.Path.GetDirectoryName(filepath)
Dim myFileList As New List(Of String)
For Each file As String In System.IO.Directory.GetFiles(directoryPath)
    'Add only dates to the list
    If (IsDate(System.IO.Path.GetFileNameWithoutExtension(file))) Then
        myFileList.Add(System.IO.Path.GetFileNameWithoutExtension(file))
    End If
Next
myFileList.OrderByDescending(Function(x) CType(x, DateTime))

Use OrderBy Or OrderBydescending to change the direction of sorting


If the Arraylist is mandatory then you still can change the output you can easily create an ArrayList from a List as follows.

Dim arr As New ArrayList(myFileList)

Upvotes: 2

Related Questions