If you call list.Remove
it will remove the first instance; you can, however, use list.RemoveAt
and list.RemoveRange
. For example:
list.RemoveRange(5,2);
or better: don't add them in the first place.
For example, if you are adding from a sequence you can use Distinct
or HashSet<T>
to find unique items when adding.
After the fact, you could use:
var dups = from item in list
group item by item into grp
where grp.Count() > 1
select grp.Key;
foreach (var val in dups)
{
int first = list.IndexOf(val), last;
while ((last = list.LastIndexOf(val)) != first)
{
list.RemoveAt(last);
}
}
To remove all but the first instance of duplicates.
Or perhaps more efficiently:
for (int i = 0; i < list.Count; i++ )
{
var val = list[i];
int first = list.IndexOf(val), last;
while ((last = list.LastIndexOf(val)) != first)
{
list.RemoveAt(last);
}
}