Aslah Fida'iyi
Aslah Fida'iyi

Reputation: 41

How can I compare items in 2 ListView controls and display the missing items?

I'm coding a program in c#. I have 2 ListView controls. listview1 is getting TagName and TagID from mysql database. listview2 is getting TagName from an external device. I would like to compare the TagName fields from the 2 listviews and display a MessageBox with the missing items if listview2 has missing items that are shown in listview1. How do I go around doing this?

So far i've tried this:

LstView.Sort();
ListViewDatabase.Sort();
if (ListViewDatabase.Items.Count > 0)
{
    for (int i = 0; i < ListViewDatabase.Items.Count; i++)
    {
        string t = ListViewDatabase.Items[i].SubItems[1].Text;

        for (int j = 0; j < LstView.Items.Count; j++)
        {
            if (t != LstView.Items[j].SubItems[1].Text)
            {
                MessageBox.Show("Missing Tag" + LstView.Items[j].SubItems[1].Text);
            }
        }
    }
}

But this just shows all the tags in listview2 and not the ones that are missing. Any help will be much appreciated.

Upvotes: 0

Views: 817

Answers (2)

Mohsen Kamrani
Mohsen Kamrani

Reputation: 7457

You can use this, just modify it based on your required fields and according to the name of the controls.

List<string> list1 = listView1.Items.Cast<ListViewItem>()
                        .Select(item => item.Text)
                        .ToList();
List<string> list2 = listView2.Items.Cast<ListViewItem>()
                        .Select(item => item.Text)
                        .ToList();
var commonUsers = list1.Select(a => a.Text).Intersect(list2.Select(b => b.Text)); // or use .Except to get the opposite

Upvotes: 0

Reza Aghaei
Reza Aghaei

Reputation: 125197

You can use such linq query to get items which are present in listView1 but are absent in listView2:

var diff = listView1.Items.Cast<ListViewItem>().Select(x => x.Text)
                    .Except(listView2.Items.Cast<ListViewItem>().Select(x => x.Text));
MessageBox.Show(string.Format("{0} Missing.", string.Join(",", diff)));

Upvotes: 1

Related Questions