tags:

views:

504

answers:

4

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
+5  A: 
Hashtable htCopy = new Hashtable();

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

ArrayList distinctArrayList = new ArrayList(htCopy.Keys);
rahul
This feels dirty and hacky, mhmm, me like!
arul
+2  A: 
// 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
phoenix's suggestion is faster
ArsenMkrt
It would be better to use `Sort` and `BinarySearch`, methods that an ArrayList already has.
Kobi
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
@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
A: 
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
@Badaro, There's no "pretty Linq" in this answer.
Ash
@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
A: 

Have you considered changing your ArrayList to IEnumerable<int>, or perhaps List<int> ?

ArrayList myAL = new ArrayList {8, 1, 1, 1, 2, 1 ,2, 3, 4, 5, 5, 5, 6 };

var myInts = (from i in myAL.Cast<int>()  
              orderby i  
              select  i).Distinct();


foreach (int i in myInts)
{
    Console.WriteLine(i);
}
p.campbell
The title says C# 2.0.
Kobi
C# 2.0 doesn't have LINQ ;) Also, you could just do `var myInts = myAL.Cast<int>().Distinct();`
280Z28