1. Computing

Remove Duplicate Items in Delphi's TStringList

By

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) ;
 var
   buffer: TStringList;
   cnt: Integer;
 begin
   stringList.Sort;
   buffer := TStringList.Create;
   try
     buffer.Sorted := True;
     buffer.Duplicates := dupIgnore;
     buffer.BeginUpdate;
     for cnt := 0 to stringList.Count - 1 do
       buffer.Add(stringList[cnt]) ;
     buffer.EndUpdate;
     stringList.Assign(buffer) ;
   finally
     FreeandNil(buffer) ;
   end;
 end;
 
Here's an example of usage:
 var
   sl : TStringList;
   cnt : integer;
 begin
   Randomize;
   sl := TStringList.Create;
   try
     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)) ;
   finally
     sl.Free;
   end;
 end;
 
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.