Monday, 11 February 2013

C# Remove duplicate numbers/records from an array

C# Remove duplicate numbers/records from an array


Suppose array has series of numbers, if user wants to extract/find duplicated number in an array.
Here is the Logic.

static void RemoveDuplicateNumbersInArray()
        {
            int[] a = new int[] { 10, 20, 10, 30, 30, 20, 40, 40, 12, 14, 12, 14 };





            var query = from d in a
                        group d by d into da
                        select da;


            a = new int[query.Count()];
            for (int i = 0; i < query.Count(); i++)
            {
                a[i] = query.ElementAt(i).Key;
            }

            foreach (int i in a)
            {
                Console.WriteLine(i);
            }
      }

Note :  1.Group each number by that number, so that duplicates will be under same group.
            2.if any group has more than one element          
                    query.Count() returns unique elements count.
            3. Then assign this values to existing array.

Input : int[] a = new int[] { 10, 20, 100, 100, 100, 10, 30, 20, 40, 50, 12, 14 };
Output:10      20      100     30      40      50      12      14


i.e 10,20,100 repeated more than once . so these are extra values removed from the array.

Input:  int[] a = new int[] { 10, 20,  10,30, 30, 20, 40, 40, 12, 14,12,14 };
Output: 10      20      30      40      12      14
 i.e 10 ,20,30,40,12,14 numbers repeated more than one time in an array a.

Tags:
C# Remove duplicate numbers/records from an array,C# Remove duplicate records from an array,C# get unique elements array,C# get unique array,IGrouping LINQ,LINQ Count,LINQ Select on IGrouping,C# Find only Duplicate Values in an Array using LINQ