Monday, 11 February 2013

C# Find only Duplicate Values in an Array

C# Find only Duplicate Values in 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 GetDuplicateElementsInArray()
        {
            int[] a = new int[] { 10, 20, 100, 100, 100, 10, 30, 20, 40, 50, 12, 14 };

              



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

               foreach (var i in query.Select((ab, bc) => ab).Where((ab, bc) => ab.Count() != 1))
                   Console.WriteLine(i.Key);

         

        }

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.Select((ab, bc) => ab.Count()) will be be greater than 1.
            3. Then filter the groups which has counter != 1  in step 2.
                 i.e this process may result more than one element.

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



i.e 10,20,100 repeated more than once . so these are duplicate values in an 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# Find only Duplicate Values in an Array,get repeated elements in an array,get non-unique values from an array,IGrouping LINQ,LINQ Count,LINQ Select on IGrouping,

No comments:

Post a Comment