1

Is is posssible to use customSort on a TStringList using the Name from the Name/Value pairs

I was currently using a TStringList to sort one value in each pos. I now need to add additional data with this value and therefor I am now using the TStringList as Name/Values

My current CompareSort is:

function StrCmpLogicalW(sz1, sz2: PWideChar): Integer; stdcall;
  external 'shlwapi.dll' name 'StrCmpLogicalW';


function MyCompare(List: TStringList; Index1, Index2: Integer): Integer;
begin
  Result := StrCmpLogicalW(PWideChar(List[Index1]), PWideChar(List[Index2]));
end;
Usage:
  StringList.CustomSort(MyCompare);

is there a way to modify this so that it sorts based on the Name of the name value pairs?

Or, is there another way?

RobertFrank
  • 7,252
  • 11
  • 50
  • 96
JakeSays
  • 1,948
  • 7
  • 27
  • 42

2 Answers2

7
function MyCompare(List: TStringList; Index1, Index2: Integer): Integer;
begin
  Result := StrCmpLogicalW(PWideChar(List.Names[Index1]), PWideChar(List.Names[Index2]));
end;

But actually, I think yours should work as well, since the string itself starts with the name anyway, so sorting by the entire string implicitly sort it by name.

GolezTrol
  • 111,943
  • 16
  • 178
  • 202
3

To solve this you use the Names indexed property which is described in the documentation like this:

Indicates the name part of strings that are name-value pairs.

When the list of strings for the TStrings object includes strings that are name-value pairs, read Names to access the name part of a string. Names is the name part of the string at Index, where 0 is the first string, 1 is the second string, and so on. If the string is not a name-value pair, Names contains an empty string.

So, instead of List[Index1] you simply need to use List.Names[Index1]. Your compare function thus becomes:

function MyCompare(List: TStringList; Index1, Index2: Integer): Integer;
begin
  Result := StrCmpLogicalW(
    PChar(List.Names[Index1]), 
    PChar(List.Names[Index2])
  );
end;
David Heffernan
  • 587,191
  • 41
  • 1,025
  • 1,442