Monday, November 1, 2021

[VB.net][Example] Sort file by last modified date, and then the file name

This function is added for custom compare feature. ordering files by last-modified date by descending-order and then if files' modified-date are same, these files with same modified-date would be sort by ascending order.

Solution

private function CompareFiles(ByVal xObj As Object, ByVal yObj As Object) As Integer

  Dim comparer As New CaseInsensitiveComparer()

  Dim x As FileInfo = Ctype(xObj, FileInfo)

  Dim y As FileInfo = Ctype(yObj, FileInfo)

  Return Iif(x.LastWriteTime = y.LastWriteTime _ 

    comparer.Compare(x.Name, y.Name), _ 

    comparer.Compare(y.LastWriteTime, x.LastWriteTime))

End function

Call functions:

Dim result As List(Of FileInfo) = New List(Of FileInfo)

result.Add(New FileInfo("C:\Source\1.txt"))

result.Add(New FileInfo("C:\Source\2.txt"))

result.Add(New FileInfo("C:\Source\3.txt"))

result.Sort(AddressOf CompareFiles)

No comments :

Post a Comment