Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi XE2 Sort Tstringlist by Filename

Tags:

sorting

delphi

I have a series of files that have various file paths and filenames in, all the file names have the same extension but the directory names or paths are all different and have set about loading the files into a Tstringlist and I am trying to sort them into filename order even though they have the paths as well.

Here is an example of the strings in the Tstringlist:-

c:\directory 1\AboutUs.lnk
c:\directory something\AAHelp.lnk
c:\directory anything\AAATalk.lnk

When sorted by the filename part of the string I would like to end up with.

c:\directory anything\AAATalk.lnk
c:\directory something\AAHelp.lnk
c:\directory 1\AboutUs.lnk

In other words I would like to be able to sort the strings with path by the filename part of the string.

Any help would be appreciated!.

like image 328
Michael Geraghty Avatar asked Nov 16 '16 01:11

Michael Geraghty


1 Answers

Use TStringList.CustomSort():

function Compare(List: TStringList; Index1, Index2: Integer): Integer;
begin
  Result := CompareStr(
    LowerCase(ExtractFileName(List[Index1])),
    LowerCase(ExtractFileName(List[Index2]))
  );
end;

// Then, just call:
YourStrList.CustomSort(Compare);
like image 56
karliwson Avatar answered Sep 28 '22 07:09

karliwson