Michael Geraghty
Michael Geraghty

Reputation: 113

Delphi XE2 Sort Tstringlist by Filename

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!.

Upvotes: 6

Views: 345

Answers (1)

karliwson
karliwson

Reputation: 3485

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);

Upvotes: 7

Related Questions