Nov 3, 2008

How to: Remove Duplicates from C# ListBox

i must admit i quite a lazy coder so if i can find a method online that i can bend to my will im stoked. every now and again i have to write my own unfortunately...
this is a simple snippet to remove duplicates from a ListBox in C# using an ArrayList. i run this method everytime i add new items.
use it, dont use it....

private void CheckDuplicates()
 {

            int r = ListBox.Items.Count;
            ArrayList newList = new ArrayList();

            //Load all Items into temp array
           string[] temp = new string[r];
            for (int i = 0; i < r; i++)
            {
                temp[i] = ListBox.Items[i].ToString();
            }

            //Add unique items to new ArrayList
            foreach (string ts in temp)
            {
                if (!newList.Contains(ts))
                {
                    newList.Add(ts);
                }
            }

            ListBox.Items.Clear();
            foreach (string ns in newList)
            {
                ListBox.Items.Add(ns.ToString());
            }

  }

5 comments:

ƒяº$τ δε√í⌠ said...

This code is for runtime mode...
which fetch only distinct elements....
just enter there below codes inside an button event(for open file dialog)....

openFileDialog2.ShowDialog();
string[] z = openFileDialog2.FileNames;
foreach (string f in z)
{
if (!listBox1.Items.Contains(f))
listBox1.Items.Add(f);
}

ƒяº$τ δε√í⌠ said...

This code is for runtime mode...
which fetch only distinct elements....
just enter there below codes inside an button event(for open file dialog)....

openFileDialog2.ShowDialog();
string[] z = openFileDialog2.FileNames;
foreach (string f in z)
{
if (!listBox1.Items.Contains(f))
listBox1.Items.Add(f);
}

Anonymous said...

Thanks!

Anonymous said...

Thanks!

lingmaaki said...

C# Listbox examples.

Ling