Reputation: 79
What I'm trying to do is remove duplicate rows in a listView but only if the 1st column is duplicated for example:
NAME / AGE / JOB
John / 24 / Engineer
Tom / 32 / Golfer
John / 55 / Scientist
The name John is in there twice, i would just prefer to have it once, and delete all other rows, this is the basic code i have so far is:
public void RemoveDuplicates() {
for (int i = 0; i < listViewTwitter.Items.Count - 1; i++)
{
if (listViewTwitter.Items[i].Tag == listViewTwitter.Items[i + 1].Tag)
{
listViewTwitter.Items[i + 1].Remove();
}
}
}
I cannot think of the best way to do it, any help would be appreciated.
Upvotes: 0
Views: 79
Reputation: 3009
The below code is an example which I wrote for you.
To make my exmaple better, First I created a class:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Job { get; set; }
}
Then I declared a list of objects of Person
class.
private void frmMain_Load(object sender, EventArgs e)
{
var list = new List<Person>()
{
new Person() { Age = 24 , Job = "Engineer", Name = "John" },
new Person() { Age = 32, Job = "Golfer", Name = "Tom " },
new Person() { Age = 55, Job = "Scientist",Name = "John" },
};
foreach (var person in list)
{
ListViewItem item = new ListViewItem(person.Name);
item.Tag = person;
listView1.Items.Add(item);
}
}
Then I remove all dupplicates by pressing a button, with two for-loop
private void btnRemoveDupplicates_Click(object sender, EventArgs e)
{
for (int i=0;i<listView1.Items.Count;i++)
{
var person = (Person)listView1.Items[i].Tag;
for (int j = 0; j < listView1.Items.Count; j++)
{
if(
((Person)listView1.Items[j].Tag).Name == person.Name &&
listView1.Items[i].Index != listView1.Items[j].Index)
{
listView1.Items[j].Remove();
continue;
}
}
}
}
Upvotes: 1