How to compare listBox1 with listBox2 if the data does not fit to display them?

I tried this, but it does not work:

for (int i = 0; i < listBox1.Items.Count; i++) { if (listBox1.Items[i] != listBox2.Items[i]) { listBox3.Items.Add(listBox2.Items[i]); } } 
  • 2
    describe in more detail exactly how to compare the elements. While you are trying to compare elements with the same numbers without taking into account that in the second list there may be less of them, which should naturally end with OutOfRangeException - rdorn
  • @Sauron, so you need to check every element of the first ListBox with all the elements of the second ListBox ? If they do not match then add to the third LisstBox ? - Lightness

1 answer 1

Since it is not clear what types you have stored in the ListBox , I will assume that there is a string . We use the Except operation, which returns a sequence containing all elements of the first sequence that are not in the second sequence.

 var exceptItems = listBox1.Items.Cast<string>().Except(listBox2.Items.Cast<string>()); foreach(string s in exceptItems) listBox3.Items.Add(s);