Delphi中的非字母排序 [英] Non alphabetic sort in Delphi
问题描述
我正在尝试按特定的顺序对TStringList进行排序.
I'm trying to sort a TStringList in an especific order.
而不是A,B,C.我正尝试在B,C,A中订购它.
Instead of A,B,C.. I'm trying to order it in B,C,A.
我已经按照需要的顺序声明了一个const数组.
I've declarated a const array with the order that I need.
我已经尝试过使用CustomSorte,但是我不明白如何编写该函数.
I've tried with CustomSorte, but I can't understand how to write the function.
我现在正在尝试for循环,但这真的很难而且令人困惑!
I'm trying with for loops now, but it is going really hard and confusing!
我不是Delphi专家...
I'm not a Delphi Expert...
谢谢你们!
推荐答案
从有关TStringListSortCompare
函数类型的帮助中:
From the help about the TStringListSortCompare
function type:
Index1和Index2是要比较的List中项目的索引. 回调返回:
Index1 and Index2 are indexes of the items in List to compare. The callback returns:
- 如果Index1标识的字符串位于Index2标识的字符串之前,则该值小于0
- 如果两个字符串相等,则为0
- 如果带有Index1的字符串位于由Index2标识的字符串之后,则该值大于0.
- 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.
因此,如果您从第一个商品的自定义订单中减去第二个商品的自定义订单,那么这些商品将按照您的意愿进行排序.
So if you subtract your custom order of the second item from the custom order of the first one, then the items will be sorted like you want.
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中的非字母排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!