Unless you absolutely have to (e.g. because you're using .NET 1), please don't use ArrayList, it's an old non-generic class. Instead, use List<T>
in the System.Collections.Generic
namespace, e.g. List<int>
or List<object>
(the latter is functionally equivalent to an ArrayList since you can add anything to it).
In general, don't use anything directly inside System.Collections
unless you're sure of what you're doing; use the collections in System.Collections.Generic
instead.
You can use the LINQ method Distinct()
on your data, but if you want to use an ArrayList you'll first need to cast it to an IEnumerable<T>
using Cast<object>()
, like so:
using System.Linq;
// ...
var distinctItems = myList.Cast<object>().Distinct();
This is equivalent to manually creating a set (e.g. HashSet<object>
), adding each item of your list to it, and them making a list out of that set, since by definition sets do not keep duplicate items (they don't complain if you insert one though, they just ignore it).