0

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
monkey_boys
  • 7,108
  • 22
  • 58
  • 82

3 Answers3

5
Hashtable htCopy = new Hashtable();

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

ArrayList distinctArrayList = new ArrayList(htCopy.Keys);
Ahmad Mageed
  • 94,561
  • 19
  • 163
  • 174
rahul
  • 184,426
  • 49
  • 232
  • 263
2
// 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"
source.Sort();
ArrayList dest = new ArrayList();
foreach (int i in source) if (dest.BinarySearch(i)<0) dest.Add(i);
Badaro
  • 3,460
  • 1
  • 19
  • 18
  • phoenix's suggestion is faster – Arsen Mkrtchyan Sep 15 '09 at 05:08
  • 1
    It would be better to use `Sort` and `BinarySearch`, methods that an ArrayList already has. – Kobi Sep 15 '09 at 05: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 05: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
0
public ArrayList RemoveDups ( ArrayList input )
{
    ArrayList single_values = new ArrayList();

    foreach( object item in input)
    {
        if( !single_values.Contains(item) )
        {
            single_values.Add(item);
        }
    }
    return single_values;
}
SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
  • @Badaro, There's no "pretty Linq" in this answer. – Ash Sep 15 '09 at 05: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