我正在尝试按特定顺序对 TStringList 进行排序。
而不是 A,B,C.. 我尝试在 B,C,A 中订购。
我已经按照我需要的顺序声明了一个 const 数组。
我尝试过 CustomSorte,但我不明白如何编写该函数。
我现在正在尝试使用 for 循环,但它真的很难而且令人困惑!
我不是 Delphi 专家...
先谢谢大家了!
最佳答案
来自有关 TStringListSortCompare
函数类型的帮助:
Index1 and Index2 are indexes of the items in List to compare. The callback returns:
- a value less than 0 if the string identified by Index1 comes before the string identified by Index2
- 0 if the two strings are equivalent
- a value greater than 0 if the string with Index1 comes after the string identified by Index2.
因此,如果您从第一个项目的自定义顺序中减去第二个项目的自定义顺序,那么项目将按照您想要的方式排序。
const
Order: array[0..6] of String = ('B', 'C', 'A', 'D', 'G', 'F', 'E');
function GetStringOrder(const S: String; CaseSensitive: Boolean): Integer;
begin
for Result := 0 to Length(Order) - 1 do
if (CaseSensitive and (CompareStr(Order[Result], S) = 0)) or
(not CaseSensitive and (CompareText(Order[Result], S) = 0)) then
Exit;
Result := Length(Order);
end;
function MyCompareStrings(List: TStringList; Index1, Index2: Integer): Integer;
begin
Result := GetStringOrder(List[Index1], List.CaseSensitive) -
GetStringOrder(List[Index2], List.CaseSensitive);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
List: TStringList;
begin
List := TStringList.Create;
try
List.CommaText := 'A,G,a,C,B,b,F,a,B,C,c,D,d,E,D,F,G,C,A,G,d,e,f,g';
List.CaseSensitive := True;
List.CustomSort(MyCompareStrings);
ListBox1.Items.Assign(List);
finally
List.Free;
end;
end;
关于delphi - Delphi 中的非字母排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7123358/