2011-07-25 97 views
5

我有一個列表框或列表視圖與項目。我有一個與列表框/列表視圖相同的項目(字符串)的字符串列表。我想從字符串列表中刪除列表框/列表視圖中的所有選定項目。從TStringList刪除字符串

怎麼辦?

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

回答

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

+1爲'Count - 1':) – 2011-07-25 20:39:05

15

的竅門是運行在相反的順序循環:

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

這樣,刪除條目的動作只會改變元素的索引後面的列表,以及這些元素已經被處理。

+5

今天速度很慢嗎? –

+0

誰是第一個? :) – maxfax

+0

@maxfax這有什麼關係誰是第一個? –

4

如何做相反的方式(添加而不是刪除)?

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

好吧,這對我來說更有意義,但是這個問題本身似乎基本上是混淆不清的。 –

+0

@warren你通常如何迭代列表並刪除一些但不是全部項目? –

9

Andreas和David提供的解決方案假定ListBox和StringList中的字符串的順序完全相同。這是一個很好的假設,因爲您沒有另行說明,但如果不是這樣,您可以使用StringList的IndexOf方法來查找字符串的索引(如果對StringList進行排序,則改爲使用Find)。類似於

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; 
+0

我想你可以肯定,maxfax正在同步維護這兩個列表,所以不需要假設任何東西 –