Delphi数据字典TDictionary

在 Delphi 中,创建一个数据字典通常意味着使用一种结构来存储键值对。Delphi 没有内建的字典类型,但你可以使用 TStringList 从 Classes 单元作为一个简单的键值对存储,或者你可以使用更复杂的第三方容器,如 TDictionary 从 Generics.Collections 单元。

以下是一个使用 TDictionary 的简单示例:

uses
  System.SysUtils, System.Generics.Collections;

var
  Dict: TDictionary<string, string>;
  Key: string;
  Value: string;
begin
  // 创建一个新的字典实例
  Dict := TDictionary<string, string>.Create;
  try
    // 添加一些键值对
    Dict.Add('Key1', 'Value1');
    Dict.Add('Key2', 'Value2');
    Dict.Add('Key3', 'Value3');

    // 遍历字典并输出键值对
    for Key in Dict.Keys do
    begin
      Value := Dict[Key];
      WriteLn(Format('Key: %s, Value: %s', [Key, Value]));
    end;

    // 检查一个特定的键是否存在,并输出其值
    if Dict.ContainsKey('Key2') then
      WriteLn(Format('Value for Key2: %s', [Dict['Key2']]))
    else
      WriteLn('Key2 not found');

    // 移除一个键值对
    Dict.Remove('Key3');

    // 再次检查已移除的键是否存在
    if Dict.ContainsKey('Key3') then
      WriteLn('Key3 still exists')
    else
      WriteLn('Key3 has been removed');
  finally
    // 释放字典实例
    Dict.Free;
  end;
end;

uses
  System.SysUtils, System.Generics.Collections;

var
  Dict: TDictionary<string, string>;
  Key: string;
  Value: string;
begin
  // 创建一个新的字典实例
  Dict := TDictionary<string, string>.Create;
  try
    // 添加一些键值对
    Dict.Add('Key1', 'Value1');
    Dict.Add('Key2', 'Value2');
    Dict.Add('Key3', 'Value3');

    // 遍历字典并输出键值对
    for Key in Dict.Keys do
    begin
      Value := Dict[Key];
      WriteLn(Format('Key: %s, Value: %s', [Key, Value]));
    end;

    // 检查一个特定的键是否存在,并输出其值
    if Dict.ContainsKey('Key2') then
      WriteLn(Format('Value for Key2: %s', [Dict['Key2']]))
    else
      WriteLn('Key2 not found');

    // 移除一个键值对
    Dict.Remove('Key3');

    // 再次检查已移除的键是否存在
    if Dict.ContainsKey('Key3') then
      WriteLn('Key3 still exists')
    else
      WriteLn('Key3 has been removed');
  finally
    // 释放字典实例
    Dict.Free;
  end;
end;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蝈蝈(GuoGuo)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值