TStringList的实用功能

1.names与values的使用

var
  tempStrList:TStringList;
begin
  tempStrList:=TStringList.Create;
  tempStrList.Add('sid'+'='+'06111');
  tempStrList.Add('sname'+'='+'Eric');

  ShowMessage(tempStrList[0]+#13#10+
              tempStrList.Names[0]+#13#10+
              tempStrList.Values['sid']+#13#10+
              tempStrList.ValueFromIndex[0]);

  tempStrList.Free;
end;

  运行结果:

 

 2.避免重复元素被添加

  tempList:=TStringList.Create;

  tempList.Sorted:=True;
  tempList.Duplicates := dupIgnore;  //如有重复值则放弃

  tempList.Delimiter:=',';
  tempList.DelimitedText:='1,2,2,3,3,4';

  ListBox2.Items.Assign(tempList);

  tempList.Free;

  //Duplicates 有3个可选值:
  //dupIgnore: 放弃;
  //dupAccept: 结束;
  //dupError: 提示错误.

 

  运行结果:

 

 3.自动排序

    排序函数:

//排序函数,此处为升序,要降序只需将-1和1交换
function   NumberSort(List:   TStringList;   Index1,   Index2:   Integer):   Integer;
var
    Value1,Value2:Integer;
begin
    Value1:=StrToInt(List[Index1]);
    Value2:=StrToInt(List[Index2]);
    if   Value1> Value2   then
        Result:=1
    else
    if   Value1 <Value2   then
        Result:=-1
    else
        Result:=0;
end;

    调用:

  tempList:=TStringList.Create;
  tempList.Add('2');
  tempList.Add('3');
  tempList.Add('1');

  ListBox1.Items.Assign(tempList);
  tempList.CustomSort(NumberSort);   
  ListBox2.Items.Assign(tempList);

  tempList.Free;

     运行结果:

   

    说明:当“避免重复元素”和“自动排序”两个功能同时使用,需要分别使用两

          个StringList,否则“自动排序”功能将无法使用。

posted @ 2012-06-18 16:31  edisonfeng  阅读(836)  评论(0编辑  收藏  举报