我有一个带有项目的列表框或列表视图。我还有一个与列表框/列表视图中相同项目(字符串)的字符串列表。我想从字符串列表中删除所有在列表框/列表视图中选择的项目。
如何实现?
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
我有一个带有项目的列表框或列表视图。我还有一个与列表框/列表视图中相同项目(字符串)的字符串列表。我想从字符串列表中删除所有在列表框/列表视图中选择的项目。
如何实现?
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
for i := ListBox.Count - 1 downto 0 do
if ListBox.Selected[i] then
StringList1.Delete(i);
窍门在于倒序运行循环:
for i := ListBox.Count-1 downto 0 do
if ListBox.Selected[i] then
StringList1.Delete(i);
这种方式,删除一个元素只会改变列表后面元素的索引位置,而这些元素已经被处理过了。
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;
StringList1.Clear;
for i:=0 to ListBox.Count-1 do
if not ListBox.Selected[i] then StringList1.Add(ListBox.Items(i));
Count-1
而不是pred(Count)
! - David Heffernan