0

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();
   }
}
6
  • 1
    This should remove duplicate entries, what result this gives? Commented Jun 17, 2015 at 6:44
  • 1
    Have you tried stepping through the code in the debugger? Commented Jun 17, 2015 at 6:45
  • By the look of it I can say that you can not modify collection while iterating. This possibly could throw eception. One suggestion, just grab indexes of the duplicates and remove it separately. Commented Jun 17, 2015 at 6:46
  • @prashanth - that would be true if OP was using a foreach loop, but they're not. Commented Jun 17, 2015 at 6:46
  • possible duplicate stackoverflow.com/questions/15572169/… Commented Jun 17, 2015 at 6:48

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Please note the link I provided. I offered a solution to the most likely error in your code, but frankly...unless you provide a proper code example, a lot of people will have to waste a lot of time before someone randomly stumbles across the correct answer, assuming that ever happens at all. With a proper code example, a solution can be provided easily and quickly (assuming you don't discover it yourself as you prepare the code example).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.