2010-04-16 61 views
2

我想刪除我的列表視圖中的重複項。刪除Delphi中的重複列表視圖

此功能:

procedure RemoveDuplicates(const LV:TbsSkinListView); 
var 
    i,j: Integer; 
begin 
    LV.Items.BeginUpdate; 
    LV.SortType := stText; 
    try 
    for i := 0 to LV.Items.Count-1 do 
    begin 
     for j:=i+1 to LV.Items.Count-1 do 
     begin 
     if SameText(LV.Items[i].SubItems[0], LV.Items[j].SubItems[0]) and 
     SameText(LV.Items[i].SubItems[1], LV.Items[j].SubItems[1]) and 
     SameText(LV.Items[i].SubItems[2], LV.Items[j].SubItems[2]) and 
     SameText(LV.Items[i].SubItems[3], LV.Items[j].SubItems[3]) then  
     LV.Items.Delete(j); 
     end; 
    end; 
    finally 
    LV.SortType := stNone; 
    LV.Items.EndUpdate; 
    end; 
    ShowMessage('Deleted');  
end; 

不會刪除重複項。它有什麼問題?

+0

它正在做什麼,你不希望它做什麼? – Nat 2010-04-16 03:43:59

+0

我的意思是它沒有刪除dublicates先生 – radick 2010-04-16 03:51:15

回答

4

在猜測,因爲你沒有提到什麼錯誤,我會認爲這是與事實,ij無效於做你,因爲你是UP計數刪除了一個項目之後。

一個更好的想法是將計算代替:

procedure RemoveDuplicates(const LV:TbsSkinListView); 
var 
    i,j: Integer; 
begin 
    LV.Items.BeginUpdate; 
    LV.SortType := stText; 
    try 
    for i := LV.Items.Count-1 downto 0 do // <- this loop now counts _down_ 
    begin 
     for j:= LV.Items.Count-1 downto i+1 do // <- this loop now counts _down_ 
     begin 
     if SameText(LV.Items[i].SubItems[0], LV.Items[j].SubItems[0]) and 
      SameText(LV.Items[i].SubItems[1], LV.Items[j].SubItems[1]) and 
      SameText(LV.Items[i].SubItems[2], LV.Items[j].SubItems[2]) and 
      SameText(LV.Items[i].SubItems[3], LV.Items[j].SubItems[3]) then  
      LV.Items.Delete(j); 
     end; 
    end; 
    finally 
    LV.SortType := stNone; 
    LV.Items.EndUpdate; 
    end; 
    ShowMessage('Deleted');  
end; 
+0

謝謝它的工作:),我做錯了,由頂部到下來 再次感謝:) – radick 2010-04-16 03:59:21

2

在Delphi IMO要做到這一點,最簡單的辦法是做這樣....

  • 創建您的匹配性判據 即創建一個 hashkey功能添加所有你想要的文字 匹配在一起,然後散列它。
  • 使用hash作爲一個關鍵的 列表
  • 瀏覽您的ListView和刪除 不在列表中的任何項目。

僞碼....(未經測試)

var 
    hash : integer; 
    i : integer; 
    list : SomeGenericList; // some generic list to contain your hash. 
Begin 
    list = SomeGenericList.Create; 
    for i := pred(lv.Items.Count) downto 0 
    begin 
     hash := GetHashValue(lv.items[i]); 
     if List.Contains(hash) 
     begin 
      lv.Items.Delete(i); 
     end else 
     begin 
      List.Add(hash); 
     end; 
    end; 
    list.free; 
end; 

恥辱德爾福沒有LINQ的類型的功能,這將是使用一個非常簡單的任務。