-1

I have a collection like this:

List<string> names = new List<string> 
    {
      "One",
      "Two"
      "One",
      "Three",
      "One",
      "One"
    };

I want to remove those extra "Ones", leaving only the first "One" in. The code below doesn't work somehow.

    foreach (var item in names)
        {
            if (names.Contains(item) && names.Count(x => x == item) > 1)
            {
                names.Remove(item);
            }
        }

What are other, cleaner options? :)

Thank you in advance.

Mefhisto1
  • 2,188
  • 7
  • 34
  • 73
  • Why do you need to check if it contains duplicates at all? This requirement would be pointless: "remove duplicates if there is only one item", so the title could be simplified with "remove duplicates". There are many duplicates like [this](http://stackoverflow.com/questions/47752/remove-duplicates-from-a-listt-in-c-sharp?rq=1) or [this](http://stackoverflow.com/questions/517935/removing-duplicates-from-a-list-collection). – Tim Schmelter Aug 07 '14 at 12:32
  • is it really necessary to remove the duplicates? there's a concept called "distinct" that iterates over a list and only returns you the existing values once! – Matthias R. Aug 07 '14 at 12:32
  • `var distinctNames = new HashSet(names)` – L.B Aug 07 '14 at 12:33

1 Answers1

10

Using Linq:

List<string> names = names.Distinct().ToList();
nsgocev
  • 4,390
  • 28
  • 37