본문 바로가기
Delphi/문법

제네릭 - 델파이 TDictionary 사용

by MonoSoft 2021. 6. 17.
728x90
반응형

TDictionary

 

TDictionary 사용을 하기 위해서는 

Generics.collections 라는 클래스를 

먼저 User 추가를 해야 사용을 할 수 있다.

 

TDictionary 는 사전이라고 생각하면 되고,

표제어(keys)가 있고 

그 내용 설명(Values)이 있는 형식이요. 

 

직접 테스트 소스를 보면서 확인해 보겠다.

화면에 버튼1, 버튼2 , 메모장을 올려 놓자~!!

 

Private 에 

iDictionary : TDictionary<String,integer>;

선을 해주쟈!

 

다음으로 Form 이벤트 중....

OnCreate와 OnClase 이벤트에 다음과 같이 작성해주쟈

iDictionary를 생성하고 파괴하는 코드인다.

 

 

다음으로 버튼1 OnClick 이벤트에 다음과 같이 코딩해주자

 

procedure TForm1.Button1Click(Sender: TObject);

var

  idx: integer;

  iStr: string;

  iKey: string;

  iValue: integer;

begin

  for idx := 0 to 19 do 

  begin

    iValue := idx;

    iKey := 'Key' + IntToStr(iValue);

    // if not iDictionary.ContainsKey(iKey) then iDictionary.Add(iKey, iValue);

    iDictionary.AddOrSetValue(iKey, iValue);

  end;

 

  for iStr in iDictionary.Keys do

  begin

    Memo1.Lines.Add(iStr + '=' + IntToStr(iDictionary.Items[iStr]));

  end;

end;

 

다음으로 버튼2 onClick 이벤트에 다음과 같이 코딩해주자

 

procedure TForm1.Button2Click(Sender: TObject);

var

  iStr: string;

  iArray: TArray<string>;

begin

  iArray := iDictionary.Keys.ToArray;

  Tarray.Sort<String>(iArray);

  memo1.Lines.Add('Sorted');

 

  for iStr in iArray do

  begin // iArray 임에 주의

    Memo1.Lines.Add(iStr+'='+IntToStr(iDictionary.Items[iStr]));

  end;

end;

 

결과 데이튼 다음과 같이 나온다.

Key13=13

Key10=10

Key9=9

Key1=1

Key0=0

Key11=11

Key15=15

Key3=3

Key16=16

Key17=17

Key6=6

Key7=7

Key19=19

Key14=14

Key8=8

Key12=12

Key4=4

Key5=5

Key18=18

Key2=2

 

Sorted

Key0=0

Key1=1

Key10=10

Key11=11

Key12=12

Key13=13

Key14=14

Key15=15

Key16=16

Key17=17

Key18=18

Key19=19

Key2=2

Key3=3

Key4=4

Key5=5

Key6=6

Key7=7

Key8=8

Key9=9

 

그 외 참고 소스 

 

type

TCity = class

  Country: String;

  Latitude: Double;

  Longitude: Double;

end;

 

const

EPSILON = 0.0000001;

 

var

  Dictionary: TDictionary<String, TCity>;  

  City, Value: TCity;

  Key: String;

begin

  { Create the dictionary. }

  Dictionary := TDictionary<String, TCity>.Create;

  City := TCity.Create;

 

  { Add some key-value pairs to the dictionary. }

  City.Country := 'Romania';

  City.Latitude := 47.16;

  City.Longitude := 27.58;

  Dictionary.Add('Iasi', City);

 

  City := TCity.Create;

  City.Country := 'United Kingdom';

  City.Latitude := 51.5;

  City.Longitude := -0.17;

  Dictionary.Add('London', City);

 

  City := TCity.Create;

  City.Country := 'Argentina';

  { Notice the wrong coordinates }

  City.Latitude := 0;

  City.Longitude := 0;

  Dictionary.Add('Buenos Aires', City);

 

{ Display the current number of key-value entries. }

writeln('Number of pairs in the dictionary: ' +

IntToStr(Dictionary.Count));

 

// Try looking up "Iasi".

if (Dictionary.TryGetValue('Iasi', City) = True) then

begin

  writeln( 'Iasi is located in ' + City.Country +

            ' with latitude = ' + FloatToStrF(City.Latitude, ffFixed, 4, 2) +

            ' and longitude = ' + FloatToStrF(City.Longitude, ffFixed, 4, 2)

           );

end

else

  writeln('Could not find Iasi in the dictionary');

 

  { Remove the "Iasi" key from dictionary. }

  Dictionary.Remove('Iasi');

 

  { Make sure the dictionary's capacity is set to the number of entries. }

  Dictionary.TrimExcess;

 

  { Test if "Iasi" is a key in the dictionary. }

  if Dictionary.ContainsKey('Iasi') then

    writeln('The key "Iasi" is in the dictionary.')

  else

    writeln('The key "Iasi" is not in the dictionary.');

 

  { Test how (United Kingdom, 51.5, -0.17) is a value in the dictionary but

  ContainsValue returns False if passed a different instance of TCity with the

  same data, as different instances have different references. }

 

  if Dictionary.ContainsKey('London') then

  begin

    Dictionary.TryGetValue('London', City);

 

    if (City.Country = 'United Kingdom') and

       (CompareValue(City.Latitude, 51.5, EPSILON) = EqualsValue) and

       (CompareValue(City.Longitude, -0.17, EPSILON) = EqualsValue) then

        writeln('The value (United Kingdom, 51.5, -0.17) is in the dictionary.')

    else

      writeln('Error: The value (United Kingdom, 51.5, -0.17) is not in the dictionary.');

 

    City := TCity.Create;

    City.Country := 'United Kingdom';

    City.Latitude := 51.5;

    City.Longitude := -0.17;

 

    if Dictionary.ContainsValue(City) then

      writeln('Error: A new instance of TCity with

                values (United Kingdom, 51.5, -0.17) matches an

                existing instance in the dictionary.')

    else

      writeln('A new instance of TCity with

                values (United Kingdom, 51.5, -0.17) does not match

                any existing instance in the dictionary.');

      City.Free;

    end

    else

      writeln('Error: The key "London" is not in the dictionary.');

 

    { Update the coordinates to the correct ones. }

    City := TCity.Create;

    City.Country := 'Argentina';

    City.Latitude := -34.6;

    City.Longitude := -58.45;

    Dictionary.AddOrSetValue('Buenos Aires', City);

 

    { Generate the exception "Duplicates not allowed". }

 

    try

      Dictionary.Add('Buenos Aires', City);

    except  on Exception do

      writeln('Could not add entry. Duplicates are not allowed.');

    end;

 

    { Display all countries. }

    writeln('All countries:');

 

    for Value in Dictionary.Values do

      writeln(Value.Country);

 

  { Iterate through all keys in the dictionary and display their coordinates. }

  writeln('All cities and their coordinates:');

  for Key in Dictionary.Keys do

  begin

    writeln(Key + ': ' + FloatToStrF(Dictionary.Items[Key].Latitude, ffFixed, 4, 2) + ', ' +

    FloatToStrF(Dictionary.Items[Key].Longitude, ffFixed, 4, 2));

    end;

 

    { Clear all entries in the dictionary. }

 

    Dictionary.Clear;

 

    { There should be no entries at this point. }

    writeln('Number of key-value pairs in the dictionary after cleaning: ' +

              IntToStr(Dictionary.Count));

 

    { Free the memory allocated for the dictionary. }

    Dictionary.Free;

    City.Free;

    readln;

end.

 

728x90
반응형

댓글