Zach
Zach

Reputation: 143

Look for equality in selected listbox items

Is it possible to compare two listboxes and their respected selected values?

Basically I want to check if listbox A's selected values == listbox B's selected values.

I tried this code, but it didn't work:

if(listA.SelectedItems == listB.SelectedItems)
{
    Console.WriteLine("equal");
}
else
{
    Console.WriteLine("not equal");
}

Upvotes: 0

Views: 301

Answers (3)

Sayse
Sayse

Reputation: 43300

The simplest way would be to check if any of the second list contains the items from the first

var listAItems = listA.SelectedItems
var listBItems = listB.SelectedItems
if(listAItems.Count == listBItems.Count &&
   listAItems.Any(i => !listBItems.Contains(i)))
    //Something missing
else
    //All there

Note: this works for all IEnumerables

I'm not sure if this answer would be more efficient for your usage than the one in the duplicate since this will return true as soon as it finds an entry that doesn't exist - The duplicates answer has the possibility to return the items that are missing

var missing = listA.SelectedItems.Except(listB.SelectedItems);
if(missing.Any())
    //something missing use the missing variable to see what

Upvotes: 0

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

You can sort both the SelectedItems collection and then use SequenceEqual.

var orderedA = listA.SelectedItems.Cast<object>().OrderBy(x=> x);  
var orderedB = listB.SelectedItems.Cast<object>().OrderBy(x=> x);
if(orderedA.SequenceEqual(orderedB))
{
    Console.WriteLine("equal");
}
else
{
    Console.WriteLine("not equal");
}

Upvotes: 2

chevhfghfghfgh
chevhfghfghfgh

Reputation: 137

You are using two properties with a different meaning for your comparison. SelectedItem is an object (could be anything depending on how you have filled the combo, ValueMember is just the name of a property to use as the actual value for the items in the ListBox.

However the two classes (ListBox and ComboBox) share the same pattern for storing their list items, so supposing that both are populated using a list of strings then your code could be

dynamic curComboItem = ComboBox1.SelectedItem.ToString();
for (i = 0; i <= ListBox1.Items.Count - 1; i++) {
    if (curComboItem == ListBox1.Items(i).ToString()) {
        Interaction.MsgBox("DATA FOUND");
        break; // TODO: might not be correct. Was : Exit For
    }
}

Upvotes: 0

Related Questions