Smarter coding techniques with arrays

Last time I discussed comparing a variable to a list of values using a PeopleCode array. Another nifty use of a PeopleCode array is for joining a list of values with a delimiter.

For example, you might want to collect a list email addresses this way, separating each item with a semicolon:


While &sqlEmails.Fetch(&email)
  If none(&mail_list) Then
    &mail_list = &mail_list | ";" | &email;
  Else
    &mail_list = &email;
End-While;

Or you may want to collect a list of values to use in an IN clause for a subsequent SQL call:


For &i = 1 to &Rowset.RowCount
  If &i = 1 Then
    &dept_list = Quote(&Rowset(&i).EMPLOYEES.DEPTID.Value);
  Else
    &dept_list = &dept_list | "," | Quote(&Rowset(&i).EMPLOYEES.DEPTID.Value);
  End-If;
End-For;
&dept_list = "(" | &dept_list | ")";

PeopleCode arrays, with its Join() method makes this task easier. The above statements can be written as:


&Array1 = CreateArrayRept("", 0);
While &sqlEmails.Fetch(&email)
  &Array1.Push(&email);
End-While;
&mail_list = &Array1.Join(";","","");

And


&Array1 = CreateArrayRept("", 0);
For &i = 1 to &Rowset.RowCount
  &Array1.Push( Quote(&Rowset(&i).EMPLOYEES.DEPTID.Value) );
End-For;
&dept_list = &Array1.Join(",");

The Join() method concatenates all items in an array with a specified separator string. By default, it also encloses the concatenated value by a pair of parenthesis. These can be overridden by specifying a 2nd and 3rd parameter.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>