4

I have 2 ListBoxs which has a set of items. The count between each ListBoxs can be same or different, if the count is same, I want to check if items between the ListBoxs are same. The items can be disordered or ordered as shown below:

ListBox1 = { "C++", "C#", "Visual Basic" };
ListBox2 = { "C#", "Visual Basic", "C++" };

Kindly help.

Archana B.R
  • 397
  • 3
  • 9
  • 24

3 Answers3

5

You could use Linq's All function

var ListBox1 = new string[] { "C++", "C#", "Visual Basic" };
var ListBox2 = new string[] { "C#", "Visual Basic", "C++" };
bool same = ListBox1.Length == ListBox2.Length 
   && ListBox1.All(s => ListBox2.Contains(s));
Netricity
  • 2,550
  • 1
  • 22
  • 28
4

You can simply use HashSet:

var hashSet1 = new HashSet<string> { "C++", "C#", "Visual Basic" };
var hashSet2 = new HashSet<string> { "C#", "Visual Basic", "C++" };

var result = hashSet1.SetEquals(hashSet2);
Ayaro
  • 144
  • 4
  • Can I do something like : var hashSet1 = new HashSet(ListBox4.Items);...??? – Archana B.R Sep 08 '12 at 09:34
  • 1
    new HashSet(listBox.Items.Cast().Select(x => x.Value)) works for me (selecting collection of values), since HashSet has a constructor with a IEnumerable argument. The result of HashSet.SetEquals is boolean. – Ayaro Sep 08 '12 at 12:02
  • 1
    The result of HashSet.SetEquals is boolean - it is true if sets are equal (A is a subset of B, B is a subset of A). Moreover all elements in hashset are unique - HashSet of { "C#", "C#" } is { "C#" }. You can read more about hashset here - http://stackoverflow.com/questions/1247442/when-should-i-use-the-hashsett-type – Ayaro Sep 08 '12 at 12:12
2

I am assuming these two are two listbox controls

if (ListBox1.Items.Count == ListBox2.Items.Count)
{
    string[] listbox1arr = ListBox1.Items.OfType<string>().ToArray();
    string[] listbox2arr = ListBox2.Items.OfType<string>().ToArray();

    bool flag = listbox1arr.Intersect(listbox2arr).Count() > 0;

    MessageBox.Show(flag : "Items are not same" : "Items are same");
}
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208