Hi everyone
Can you please let me know how I can compare two listbox items in C sharp?.For example if I have a listBox 1 populated with 5 city names as[Vancouver,Richmond, Delta, Surrey,Burnaby] and another list box called listBox2 and contains 7 city names as [Vancouver,Richmond, Delta, Surrey,Burnaby, Coquitlam, Mission].How can I disaplay the intersect and differences of two list boxes in two listbox as share List and different list?

Thanks

Recommended Answers

All 4 Replies

there are many ways you can loop through listBox2 for each item of listbox1 as

for(int i=0;i<listBox1.Items.Count;i++)
{
for(int j=0;j<listBox2.Items.Count;j++)
{
if(listBox1.Items[i]==listBox2.Items[j])
{
MessageBox.Show("Matched"):
// Your Code
break;
}
}
}

another very simple way is to find the index of a specific Item in listBox 2

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
           // int i=0;
           // while (listBox1.SelectedItem != listBox2.Items[i])
           
          // if (listBox2.Items[i] == listBox1.SelectedItem)
          listBox2.SelectedIndex = listBox2.Items.IndexOf(listBox1.SelectedItem);
                
        }

Try using LINQ!
Made a form with two listboxes and the names you have, it gave me the correct results.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ListBoxLINQ
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // Just setting my first steps in LINQ here
            // Anyone who can inform me to do better, please do!
            var list1 = listBox1.Items.Cast<string>();
            var list2 = listBox2.Items.OfType<string>();

            /*----------------------------------------*/
            IEnumerable<string> ListIntersect = list1.Intersect(list2);
            string message = "The intersection is : \n";
            foreach (string name in ListIntersect)
            {
                message += name + "\n";
            }
            MessageBox.Show(message);

            /*----------------------------------------*/
            IEnumerable<string> ListDifference;
            if (list1.Count() > list2.Count())
            {
                ListDifference = list1.Except(list2);
            }
            else
            {
                ListDifference = list2.Except(list1);
            }
            message = "The difference is : \n";
            foreach (string name in ListDifference)
            {
                message += name + "\n";
            }
            MessageBox.Show(message);
        }
    }
}

Check this code:

public Form1()
        {
            InitializeComponent();
            listBox1.Items.AddRange(new string[] { "a", "b", "c" });
            listBox2.Items.AddRange(new string[] { "a", "c", "d", "e" });
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<string> list1 = new List<string>();
            List<string> list2=new List<string>();
            foreach (string item in listBox1.Items)
                list1.Add(item);
            foreach (string item in listBox2.Items)
                list2.Add(item);

            //newList will include all the common data between the 2 lists
            var diff1 = list1.Intersect(list2);
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("All common items from both lists:");
            foreach (var item in diff1)
                sb.AppendLine(item);
            var a = list1.Except(list2).ToList();
            var b = list2.Except(list1).ToList();
            var diff2 = a.Union(b);
            sb.AppendLine("\nAll different items fom both lists:");
            foreach (var item in diff2)
                sb.AppendLine(item);
            MessageBox.Show(sb.ToString());
        }

public Form1()
{
InitializeComponent();
var list1 = listBox1.Items.OfType<string>();
var list2 = listBox2.Items.OfType<string>();

        IEnumerable<string> Intersect = list1.Intersect(list2);
        IEnumerable<string> Difference = list1.Except(list2);


        listBox3.Items.AddRange(Intersect.ToArray());
        listBox4.Items.AddRange(Difference.ToArray());
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.