Removing duplicate in an Arraylist C#

Hi;

I need to remove duplicate in an Arraylist of C#. I don't want to change it to a list.

What to do?

Sample code?

Regards.
LVL 12
jazzIIIloveAsked:
Who is Participating?
 
Kyle AbrahamsSenior .Net DeveloperCommented:
Can you linq it?


            ArrayList l = new ArrayList();

Var DistinctItems =             l.AsQueryable().OfType<int>().Distinct();
0
 
anarki_jimbelCommented:
If you really want to keep ArrayList, you may use the following code.
Not very efficient but if your lists are not that big it should work OK. You create a new list and assign it finally to the original one. It would be a bit tricky to remove list items from original list :).

        private void button9_Click(object sender, EventArgs e)
        {
            ArrayList al = new ArrayList( );
            al.AddRange(new int[]{1,3,9,4,9,5,7,9,0,2,6,2});

            ArrayList al_temp = new ArrayList();
            printArrayList(al);
            foreach (int i in al)
            {
                if(!al_temp.Contains(i))
                {
                    al_temp.Add(i);
                }
            }
            al = al_temp;
            printArrayList(al);


        }
        // prints into output window
        private void printArrayList(ArrayList al)
        {
            
            foreach(int i in al)
            {
                System.Diagnostics.Debug.Write(" " + i + " ");
            }
            System.Diagnostics.Debug.WriteLine("");
        }

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.