How to compare items between two unordered ListBox

I have 2 ListBoxs that has a collection of items. The number between ListBoxs can be the same or different, if the counter is the same, I want to check if the items between ListBoxs same. Elements can be disordered or ordered, as shown below:

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

Please help.

+4
source share
3 answers

You can simply use the HashSet:

 var hashSet1 = new HashSet<string> { "C++", "C#", "Visual Basic" }; var hashSet2 = new HashSet<string> { "C#", "Visual Basic", "C++" }; var result = hashSet1.SetEquals(hashSet2); 
+4
source

You can use the Linq 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)); 
+5
source

I assume these two controls are two lists

 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"); } 
+2
source

Source: https://habr.com/ru/post/1433113/


All Articles