TStringlist Name Value pair

TStringlist
Delphi provides TStringlist class to main list of strings easily. We can store, delete, find and sort list of string in a TStringlist object. With this blog I guess you have some idea and used TStringlist.

But TStringlist provides a distinct feature that allows to store Name and Value pair as a list item at a same time like 'James=1' in which James=Name and 1=Value.

And some TStringlist properties or methods used for Name and Value pair are...

NameValueSeparator 
A symbol character that used to differentiate Name and Value in the pair
Ex.. James=1
= is NameValueSeparator

Names
Store list of Names in a string list like JAMES, KYRA, PETE, RUHI, SUNNY

Values
Store list of Values assigned to Names in a string list like 1,2,3,4,5

How to add to Stringlist?

slStudent.Add('James=1'); 
// Jame as Name, = as NameValueSeparator, 1 as Value //

IndexOfName 
Returns Index of Name stored in TStringlist when using name/value pairs. 

Difference between IndexOfName and IndexOf
Both function will return Index of a TStringlist Item but when we store as  Name=value pair in TStringlist then we should use IndexOfName function with passing Name. And when we store normal string without any pair then we should use IndexOf function.

ValueFromIndex 
Returns Value from an index of an Item starting at (0) when using name/value pairs. 

Let's see with an example...

var
  slStudent: TStringList;
  iIndex : integer;
  sname, svalue, svalueindex: string;
begin
  slStudent := TStringList.Create;
  slStudent.Clear;
  slStudent.NameValueSeparator := '=';
  slStudent.Add('JAMES=1'); // name=value pair //
  slStudent.Add('KYRA=2');
  slStudent.Add('PETE=3');
  slStudent.Add('RUHI=4');
  slStudent.Add('SUNNY=5');
   
  sname := slStudent.Names[1];
  svalue := slStudent.Values[1];  

  iindex := slStudent.IndexOfName('RUHI');
  
  svalueindex:= slStudent.ValueFromIndex(iindex);
end;

results will be...

sname = KYRA
svalue = 2
iindex  = 3
svalueindex = 4 


Comments

  1. One detail that is not mentioned is that slStudent.Strings[1] = 'JAMES=1' and Delphi components generally use the strings property, probably because it will always have a value where names and values only get assigned when the NameValueSeparator is detected. This gives you a comboBox or checklist box that doesn't display the name part by itself.

    ReplyDelete

Post a Comment

Popular posts from this blog

ShellExecute in Delphi

How to send Email in Delphi?

Variants in Delphi. Use of Variant Array. How to check a Variant is unassigned or empty or clear ?