max*_*fax 6 delphi string 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
Run Code Online (Sandbox Code Playgroud)
And*_*and 21
for i := ListBox.Count - 1 downto 0 do
if ListBox.Selected[i] then
StringList1.Delete(i);
Run Code Online (Sandbox Code Playgroud)
Dav*_*nan 17
诀窍是以相反的顺序运行循环:
for i := ListBox.Count-1 downto 0 do
if ListBox.Selected[i] then
StringList1.Delete(i);
Run Code Online (Sandbox Code Playgroud)
这样,删除项目的行为仅改变列表中稍后的元素索引,并且这些元素已经被处理.
ain*_*ain 10
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;
Run Code Online (Sandbox Code Playgroud)
反过来(添加而不是删除)如何做呢?
StringList1.Clear;
for i:=0 to ListBox.Count-1 do
if not ListBox.Selected[i] then StringList1.Add(ListBox.Items(i));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18160 次 |
| 最近记录: |