I want to sort filenames based on multiple criterias however i have found a solution based on only one, the following expression:
arr_TxtFilesToProcess.Orderby(Function(x)CInt(Split(Path.GetFileNameWithoutExtension(x),“_”)(3))).ToArray
My filenames format are as follows:
COMPANY_ACCOUNTNUM_20240826_1271_33.txt
COMPANY_ACCOUNTNUM_20240826_1272_33.txt
COMPANY_ACCOUNTNUM_20240826_1270_35.txt
COMPANY_ACCOUNTNUM_20240826_1270_36.txt
COMPANY_ACCOUNTNUM_20240826_1271_34.txt
COMPANY_ACCOUNTNUM_20240826_1272_34.txt
COMPANY_ACCOUNTNUM_20240826_1271_35.txt
COMPANY_ACCOUNTNUM_20240826_1272_35.txt
It needs to be sorted based on the last two criterias in ascending order. (1271_33)
Right order:
COMPANY_ACCOUNTNUM_20240826_1270_35.txt
COMPANY_ACCOUNTNUM_20240826_1270_36.txt
COMPANY_ACCOUNTNUM_20240826_1271_33.txt
COMPANY_ACCOUNTNUM_20240826_1271_34.txt
COMPANY_ACCOUNTNUM_20240826_1271_35.txt
COMPANY_ACCOUNTNUM_20240826_1272_33.txt
COMPANY_ACCOUNTNUM_20240826_1272_34.txt
COMPANY_ACCOUNTNUM_20240826_1272_35.txt
I assume company/accountnum are variable, otherwise it is just alphabetical order
But I assume you cn change the cint(split… part with a matching regex expression for the ####_##.txt part?
Using the pattern in the screenshot it should be something like: arr_TxtFilesToProcess.Orderby(Function(x)Regex.Match(Path.GetFileName,"(?<=_)\d{4}_\d{2,3}(?=\.txt)").ToString).ToArray
I advise including the extention in the pattern, since it’s a nice anchor to link the pattern to, in case other number combinations matching the pattern ever are in a filename leading to false positives.
arr_TxtFilesToProcess.OrderBy(Function(file)
Dim parts = Split(Path.GetFileNameWithoutExtension(file), "_"c)
(CInt(parts(3)), CInt(parts(4)))
End Function).ToArray()
(From x in arr_TxtFilesToProcess
Let m = System.Text.RegularExpressions(x,"(\d{4})_(\d{2})(?=\.)")
Let n1 = CInt(m.Groups(1).Value)
Let n2 = CInt(m.Groups(2).Value)
Order By n1,n2
Select v=x).toArray
I have tried by using the regex option, i’ve tweaked your proposed solution to this:
arr_TxtFilesToProcess.Orderby(Function(x) system.Text.RegularExpressions.Regex.Match(Path.GetFileName(x),“\d+_\d+(?=.txt)”).ToString).ToArray
But it didn’t went the way i wanted.
The result was as follows:
COMPANY_ACCOUNTNUM_20240826_1271_1.txt
COMPANY_ACCOUNTNUM_20240826_1271_10.txt
COMPANY_ACCOUNTNUM_20240826_1271_11.txt
…
COMPANY_ACCOUNTNUM_20240826_1271_2.txt
COMPANY_ACCOUNTNUM_20240826_1271_3.txt
COMPANY_ACCOUNTNUM_20240826_1272_1.txt
COMPANY_ACCOUNTNUM_20240826_1272_10.txt
…
It did sorted by the first criteria but second one was not well ordered.
The solution proposed by @lrtetala worked.
arr_TxtFilesToProcess.Orderby(Function(x) (CInt(Split(Path.GetFileNameWithoutExtension(x),““)(3)),CInt(Split(Path.GetFileNameWithoutExtension(x),””)(4)))).ToArray