0

I have duplicates in my arraylist and want to remove those duplicates to make it distinct. I tried using the hastable to get rid of duplicates but it ruins the order. How can I make it distinct without changing the insertion order?

m0g
  • 969
  • 2
  • 15
  • 30

3 Answers3

4

How about:

using System.Linq;

myArrayList = new ArrayList(myArrayList.Distinct().ToArray());

or

var myArray = myArrayList.Distinct().ToArray();
Danny Varod
  • 17,324
  • 5
  • 69
  • 111
  • 2
    `ArrayList` doesn't take an `IEnumerable`. You need to add `ToArray()` after the `Distinct()`. That said, a `List` is preferable to an `ArrayList`, despite that being the OP's current collection. – Ahmad Mageed May 18 '11 at 18:06
  • I don't usually use ArrayLists, the collections I use usually receive and IEnumberable to their constructor. If that is the case and you want an ArrayList and not an Array (as in my 2nd example), then you might have to copy the values one by one (unless it has an .AddRange() method). – Danny Varod May 18 '11 at 18:15
  • 2
    Thanks for that info but you can't use Distinct() on an arralist. I had to convert my arraylist to an array then use distinct and then convert it back to an arraylist. I was able to get there with your help though. Thanks! – m0g May 18 '11 at 18:58
0

Hashtable does sounds like a pretty good idea.

foreach object in the ArrayList:
if (object in hashtable)
{
   remove object from ArrayList. (instead of object you can use object's hash)
   // (notice, the ArrayList's indexes will change after you remove!)
}
else
{
   insert object to Hashtable.  (instead of object you can use object's hash)
}

After this run you will have only the first instance of each object.

Notice you don't have to use HashTable, even another ArrayList will suffice. Nevertheless I would go with hashtable because search/insert in hashtable is O(1) in the average case, while binary search in arraylist is O(log(n)).

TCS
  • 5,790
  • 5
  • 54
  • 86
  • If they're duplicates, first or last instance would be irrelevant – Angelo R. May 18 '11 at 18:04
  • @Angelo, I think I don't quite understand your comment... Obviously if there are duplicates than one of the duplicated instances is irrelevant, but you need to find it in order to remove it... – TCS May 18 '11 at 18:11
0

Sebastian is right. Technically if you are trying to avoid duplicates, use a collection that doesn't support duplicates. Use a Hashtable, loop through your ArrayList and pop them into it. If all the code is yours, see if you can refactor so that you're not using an ArrayList

Angelo R.
  • 2,285
  • 1
  • 17
  • 22