关键是dupIgnore决定了添加时的判断
function TStringList.AddObject(const S: string
AObject: TObject): Integer;
begin
if not Sorted then
Result := FCount
else
if Find(S, Result) then {!!这里如果找到重复项}
case Duplicates of
dupIgnore: Exit
{不添加重复项}
dupError: Error(@SDuplicateString, 0);
end;
InsertItem(Result, S, AObject);
end;
{这个是查找是否有重复项的方法}
function TStringList.Find(const S: string
var Index: Integer): Boolean;
var
L, H, I, C: Integer;
begin
Result := False;
L := 0;
H := FCount - 1;
while L <= H do
begin
I := (L + H) shr 1;
C := CompareStrings(FList^.FString, S);
if C < 0 then L := I + 1 else
begin
H := I - 1;
if C = 0 then
begin
Result := True;
if Duplicates <> dupAccept then L := I;
end;
end;
end;
Index := L;
end;
我建议你,最简单省事的方法:
procedure TForm1.Button1Click(Sender: TObject);
var
sl:TStringList;
begin
sl:=TStringList.Create;
try
sl.Duplicates:=dupIgnore;
sl.Sorted:=true;
sl.Assign(listbox1.Items);
listbox1.Items.Assign(sl);
finally
sl.Free;
end;
end;