【问题标题】:TStringList CustomSort method on Name/Value pairs名称/值对上的 TStringList CustomSort 方法
【发布时间】:2013-03-20 04:38:59
【问题描述】:

可以使用名称/值对中的名称在 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);

有没有办法修改它,使其根据名称值对的名称进行排序?

或者,还有其他方法吗?

【问题讨论】:

    标签: delphi delphi-2010


    【解决方案1】:
    function MyCompare(List: TStringList; Index1, Index2: Integer): Integer;
    begin
      Result := StrCmpLogicalW(PWideChar(List.Names[Index1]), PWideChar(List.Names[Index2]));
    end;
    

    但实际上,我认为你的应该也可以,因为无论如何字符串本身都是以名称开头的,所以按整个字符串排序隐含地按名称排序。

    【讨论】:

      【解决方案2】:

      要解决这个问题,您可以使用文档中描述的 Names 索引属性,如下所示:

      表示作为名称-值对的字符串的名称部分。

      当 TStrings 对象的字符串列表包含以下字符串时 是名称-值对,读取名称以访问字符串的名称部分。 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;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多