2

So my code is basically this:

List list = new List(new int[] { 1, 5, 8, 8, 8, 2, 3, 3, 4, }); list = RemoveDuplicats(list);

public static List<int> RemoveDuplicats(List<int> list)
{
   int i = 0;
   while (i<list.Count)
      {
        if (list[i] == list[i+1])
          {
            list.RemoveAt(list[i + 1]);
            return list;
          }
          i++;
      }
    return list;
  }

It seems like RemoveAt is not working or it's being skipped entirely. So what i should be getting is 1,5,8,2,3,4 but it just prints original list. Where'd i go wrong?

Dmitri Petrov
  • 57
  • 1
  • 1
  • 3

2 Answers2

17

Use the Distinct IEnumerable extension

List<int> list = new List<int>() { 1, 5, 8, 8, 8, 2, 3, 3, 4, }; 
list = list.Distinct().ToList();

Returns distinct elements from a sequence by using the default equality comparer to compare values.

However, a part from this solution that is explained in many duplicates of your question, I wish to explain your error.

Your current code doesn't work correctly because when you find the first duplicate you call RemoveAt passing the value of the element (8), not the index (2) of the element to be removed as RemoveAt requires. And you are lucky that this doesn't create an Out of Range exception. Moreover you exit immediately with a return leaving the other duplicates in place.

If you still want to use an hand made remove code you could try with this

public List<int> RemoveDuplicats(List<int> list)
{
    int i = 0;
    List<int> distinctElements = new List<int>();
    while (i < list.Count)
    {
        if (!distinctElements.Contains(list[i]))
            distinctElements.Add(list[i]);
        i++;
    }
    return distinctElements;
}
Steve
  • 213,761
  • 22
  • 232
  • 286
1

I would use distinct.

list.Distinct().ToList()
Undo
  • 25,519
  • 37
  • 106
  • 129
user1784014
  • 234
  • 1
  • 12