user2955299
user2955299

Reputation: 21

Remove Duplicate items from listview

I have bound the data to ListView from multiple sources. And there is duplicate data, I want to remove all the duplicates from that ListView. I used the following code but it is not helping.

listview.Sorting = System.Windows.Forms.SortOrder.Ascending;
for (int i = 0; i < listview.Items.Count - 1; i++)
{
   if (listview.Items[i].Tag == listview.Items[i + 1].Tag)
   {
      listview.Items[i + 1].Remove();
   }
}

Upvotes: 0

Views: 1663

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70652

Without a good, minimal, complete code example, it's not possible to know for sure what the problem is. However, most likely your Tag values are reference types and not actually identical object instances.

Assuming the objects override the Equals() method, you can fix it by using that method instead:

listview.Sorting = System.Windows.Forms.SortOrder.Ascending;
for (int i = 0; i < listview.Items.Count - 1; i++)
{
   if (listview.Items[i].Tag.Equals(listview.Items[i + 1].Tag))
   {
      listview.Items[i + 1].Remove();
      i--;
   }
}

Note that you also had a bug in which you would skip checking elements if there were three or more duplicates of a given value. You can fix this by decrementing i when you remove an element (see above).

Upvotes: 1

Related Questions