开发者

Delete strings from TStringList

开发者 https://www.devze.com 2023-03-23 07:46 出处:网络
I have a List Box or a List View with items. And I have a String List with the same items (strings) as the List Box/List View. I want to delete all selected items in the List Box/List View from the St

I have a List Box or a List View with items. And I have a String List with the same items (strings) as the List Box/List View. I want to delete all selected items in the List Box/List View from the String List.

How to do?

for i:=0 to ListBox.Count-1 do
  if ListBox.Selected[i] then
 开发者_如何学JAVA   StringList1.Delete(i); // I cannot know exactly an index, other strings move up


for i := ListBox.Count - 1 downto 0 do
  if ListBox.Selected[i] then
    StringList1.Delete(i);


The trick is to run the loop in reverse order:

for i := ListBox.Count-1 downto 0 do
  if ListBox.Selected[i] then 
    StringList1.Delete(i);

This way, the act of deleting an item only changes the indices of elements later in the list, and those elements have already been processed.


Solution provided by Andreas and David assumes that the strings are exactly in same order in both ListBox and StringList. This is good assumption as you don't indicate otherwise, but in case it is not true you can use StringList's IndexOf method to find the index of the string (if the StringList is sorted, use Find instead). Something like

var x, Idx: Integer;
for x := ListBox.Count - 1 downto 0 do begin
   if ListBox.Selected[x] then begin
      idx := StringList.IndexOf(ListBox.Items[x]);
      if(idx <> -1)then StringList.Delete(idx);
   end;
end;


How about doing it the other way round (adding instead of deleting)?

StringList1.Clear;
for i:=0 to ListBox.Count-1 do
  if not ListBox.Selected[i] then StringList1.Add(ListBox.Items(i));
0

精彩评论

暂无评论...
验证码 换一张
取 消