1. Computing

Remove Duplicate Items in Delphi's TStringList


Tip submitted by Jens Borrisholt

The non-visual component Delphi class, TStringList, stores and manipulates a list of strings. Each string can be associates with an object.

The TStringList is derived from the base class for storing strings, TStrings.

Many Delphi controls like TListBox, TComboBox and TMemo, for example, expose a property which is of the TStrings type: Items for TListBox, Lines for TMemo.

Removing Duplicates from a TStringList

When you fill in a string list with string items you might end up with a list holding duplicate strings - more than one item with the "same" string value.

To remove duplicate values from the string list use the following procedure:

 //remove duplicate strings from the string list
 procedure RemoveDuplicates(const stringList : TStringList) ;
   buffer: TStringList;
   cnt: Integer;
   buffer := TStringList.Create;
     buffer.Sorted := True;
     buffer.Duplicates := dupIgnore;
     for cnt := 0 to stringList.Count - 1 do
       buffer.Add(stringList[cnt]) ;
     stringList.Assign(buffer) ;
     FreeandNil(buffer) ;
Here's an example of usage:
   sl : TStringList;
   cnt : integer;
   sl := TStringList.Create;
     for cnt := 1 to 1000 do
       sl.Add(IntToStr(Random(2000))) ;
     ShowMessage('With duplicates: ' + #13#10 + IntToStr(sl.Count)) ;
     RemoveDuplicates(sl) ;
     ShowMessage('Without duplicates: ' + #13#10 + IntToStr(sl.Count)) ;
Note: Randomize initializes the random number generator; Random returns a randomly generated number within a specified range.

Delphi tips navigator:
» Get Enum information Using Delphi's RTTI
« Edit and Display Boolean Fields using a CheckBox in Delphi's DBGrid

©2014 About.com. All rights reserved.