简体   繁体   English

名称/值对上的TStringList CustomSort方法

[英]TStringList CustomSort method on Name/Value pairs

Is is posssible to use customSort on a TStringList using the Name from the Name/Value pairs 使用名称/值对中的名称可以在TStringList上使用customSort

I was currently using a TStringList to sort one value in each pos. 我目前正在使用TStringList在每个pos中对一个值进行排序。 I now need to add additional data with this value and therefor I am now using the TStringList as Name/Values 我现在需要使用此值添加其他数据,因此我现在使用TStringList作为名称/值

My current CompareSort is: 我当前的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);

is there a way to modify this so that it sorts based on the Name of the name value pairs? 有没有办法修改它,使其根据名称值对的Name排序?

Or, is there another way? 或者,还有另一种方法吗?

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. 但是实际上,我认为您的字符串也应该工作,因为字符串本身始终以名称开头,因此按整个字符串排序会隐式按名称排序。

To solve this you use the Names indexed property which is described in the documentation like this: 为了解决这个问题,您可以使用“ Names索引属性,该属性在文档中有如下描述:

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. 当TStrings对象的字符串列表包含名称-值对的字符串时,请读取“名称”以访问字符串的名称部分。 Names is the name part of the string at Index, where 0 is the first string, 1 is the second string, and so on. Names是索引处字符串的名称部分,其中0是第一个字符串,1是第二个字符串,依此类推。 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] . 因此,只需使用List.Names[Index1] List[Index1]代替List[Index1] 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM