Take the 2-minute tour ×

How to union data in ArrayList C# in dotnet framework 2?

example of data : 1, 2, 2, 3, 4, 5, 5, 6, 6
how to get 1, 2, 3, 4, 5, 6
share|improve this question

3 Answers 3

up vote 2 down vote accepted
// Assuming your data is an ArrayList called "source"
ArrayList dest = new ArrayList();
foreach(int i in source) if(!dest.Contains(i)) dest.Add(i);

You should be using List<int> instead of ArrayList, though.

Edit: Alternate solution using Sort+BinarySearch, as suggested by Kobi:

// Assuming your data is an ArrayList called "source"
ArrayList dest = new ArrayList();
foreach (int i in source) if (dest.BinarySearch(i)<0) dest.Add(i);
share|improve this answer
phoenix's suggestion is faster –  ArsenMkrt Sep 15 '09 at 5:08
It would be better to use Sort and BinarySearch, methods that an ArrayList already has. –  Kobi Sep 15 '09 at 5:10
ArsenMkrt: did you profile it? It really depends on the input dataset, but instantiating a hashtable and copying the data into a new arraylist is kinda expensive process. –  arul Sep 15 '09 at 5:15
@arul I just did some very rough testing, for an array with <100 items mine was a faster, but otherwise the Hashtable solution was (much) better. I also tested Kobi's suggestion of using Sort+BinarySearch, but it was still inferior to using a Hashtable. –  Badaro Sep 15 '09 at 14:22
Hashtable htCopy = new Hashtable();

foreach (int item in arrListFull) 
    htCopy[item] = null;

ArrayList distinctArrayList = new ArrayList(htCopy.Keys);
share|improve this answer
This feels dirty and hacky, mhmm, me like! –  arul Sep 15 '09 at 5:05
public ArrayList RemoveDups ( ArrayList input )
    ArrayList single_values = new ArrayList();

    foreach( object item in input)
        if( !single_values.Contains(item) )
    return single_values;
share|improve this answer
@Badaro, There's no "pretty Linq" in this answer. –  Ash Sep 15 '09 at 5:20
@Ash Check the history, the author removed the Linq part (which is why I removed my comment as well). He probably did it because the question said C# 2.0, but I think he should also have kept both examples. –  Badaro Sep 15 '09 at 12:08

Your Answer


