在 Delphi 中,可以使用 TList 或 TDictionary 等容器来存储元素,并通过以下方式进行去重操作:
1. 对于 TList 类型的容器,可以使用 Sort 方法将元素排序,然后使用 DeleteDuplicates 方法去除重复元素。示例代码如下:
```
var
List: TList<Integer>;
begin
List := TList<Integer>.Create;
try
// 添加元素
List.AddRange([1, 2, 3, 2, 4, 3]);
// 排序并去重
List.Sort;
List.DeleteDuplicates;
// 输出结果
for var I in List do
Writeln(I);
finally
List.Free;
end;
end;
```
2. 对于 TDictionary 类型的容器,可以用其 Key 属性作为唯一标识符来保证元素不会重复,因此直接添加元素即可。示例代码如下:
```
var
Dictionary: TDictionary<Integer, string>;
begin
Dictionary := TDictionary<Integer, string>.Create;
try
// 添加元素
Dictionary.Add(1, 'A');
Dictionary.Add(2, 'B');
Dictionary.Add(3, 'C');
Dictionary.Add(2, 'D'); // 重复元素不会被添加
// 输出结果
for var Pair in Dictionary do
Writeln(Pair.Key, ': ', Pair.Value);
finally
Dictionary.Free;
end;
end;
Copyright © 2014 DelphiW.com 开发 源码 文档 技巧 All Rights Reserved
晋ICP备14006235号-8 晋公网安备 14108102000087号
执行时间: 0.044176816940308 seconds