Anyone have a quick method for de-duplicating a generic List in C#?
If you don't care about the order you can just shove the items into a HashSet
, if you do want to maintain the order you can do something like this:
var unique = new List();
var hs = new HashSet();
foreach (T t in list)
if (hs.Add(t))
unique.Add(t);
Or the Linq way:
var hs = new HashSet();
list.All( x => hs.Add(x) );
Edit: The HashSet
method is O(N)
time and O(N)
space while sorting and then making unique (as suggested by @lassevk and others) is O(N*lgN)
time and O(1)
space so it's not so clear to me (as it was at first glance) that the sorting way is inferior (my apologies for the temporary down vote...)