Employers - Post Free Jobs
Forum guidelines
  • Home
  • »
  • C# Language
  • »
  • Hi, I am trying to remove duplicate elements from the integer array. Please see my code.
AuthorQuestion
Hi, I am trying to remove duplicate elements from the integer array. Please see my code.
Posted on: 25 Nov 2012
     Console.WriteLine("Enter the number");
            int num = Convert.ToInt32(Console.ReadLine());
            int[] array = new int[num];
            Array.Sort(array);
            for(int i = 0;i < array[i] ;i++)
            {
                if (array[0] == array[i])
                { 
                    
                }
            }


I have sorted and i am comparing every element of the array with the next element.
But how to remove the duplicate element??


AuthorReply
Vulpes
  • 1
  • 0
accepted
Re: Hi, I am trying to remove duplicate elements from the integer array. Please see my code.
Posted on: 25 Nov 2012   Accepted Answer
You can't remove anything from an array because, once you've created it, it remains fixed in size.

To remove duplicate elements, you need to convert the array to a List. You also need to iterate backwards through the list to avoid messing up the indexing of those elements which are yet to be examined.

The following program does that and also shows how simple something like this has become since the introduction of LINQ. Notice that LINQ doesn't need to sort the elements first - they maintain their original order.

using System;
using System.Collections.Generic;
using System.Linq;


class Test
{
   static void Main()
   {
      int[] array = {2, 7, 2, 4, 5, 1, 8, 1, 9, 2};

      // remove duplicates using 'traditional' code
      List<int> list = new List<int>(array);
      list.Sort();
      for(int i = list.Count - 1; i >= 1; i--)
      {
         if (list[i] == list[i-1]) list.RemoveAt(i);
      }
      int[] array2 = list.ToArray();
      foreach(int i in array2) Console.Write("{0} ", i);
      Console.WriteLine();

      // now remove them using LINQ:
      int[] array3 = array.Distinct().ToArray(); // that's it!
      foreach(int i in array3) Console.Write("{0} ", i);
      Console.WriteLine();
      Console.ReadKey();
   }
}

The output should be:

1 2 4 5 7 8 9
2 7 4 5 1 8 9

SPONSORED BY

Offshore Software and Database Development
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.