可以使用名称/值对中的名称对TStringList使用customSort
我目前使用TStringList在每个pos中排序一个值。我现在需要使用此值添加额外的数据,因此我现在使用TStringList作为名称/值
我当前的CompareSort是:
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);
是否有一种方法可以修改它,以便它根据名称值对的名称进行排序?
或者,还有别的方法吗?
function MyCompare(List: TStringList; Index1, Index2: Integer): Integer;
begin
Result := StrCmpLogicalW(PWideChar(List.Names[Index1]), PWideChar(List.Names[Index2]));
end;
但实际上,我认为你的应该也能工作,因为字符串本身以名称开头,所以按整个字符串进行排序隐式地按名称排序
要解决这个问题,您可以使用Names
索引属性,该属性在文档中有如下描述:
名称-值对字符串的名称部分
当TStrings对象的字符串列表包含以下字符串时是名称-值对,读取Names以访问字符串的名称部分。Names是Index处字符串的名称部分,其中0是第一个字符串,1是第二个字符串,以此类推。如果字符串不是名称-值对,Names包含一个空字符串。
因此,您只需使用List.Names[Index1]
而不是List[Index1]
。这样比较函数就变成:
function MyCompare(List: TStringList; Index1, Index2: Integer): Integer;
begin
Result := StrCmpLogicalW(
PChar(List.Names[Index1]),
PChar(List.Names[Index2])
);
end;