Monday, 13 February 2017

C# find repeated numbers in an array


Integer Array has  numbers ,some are repeated, if you want to find which number is repeated how many time., Here is the logic using LINQ.

       static   void FindRepeatedNumbers()
        {
             int[] arraytest = new int[] { 50, 20, 100, 10, 30, 10, 30, 20};

            var query = from d in arraytest
                        group d by d into test
                        select test;

            foreach (IGrouping<int, int> intagroup in query)
            {
                Console.WriteLine("Key={0},Repeated {1} Times", intagroup.Key, intagroup.Count());
            }
   }

  1. First group by  each number
  2. there will a unique groups ,then find each group has how many numbers.
Here is the output.

Number=50,Repeated 1 Times
Number=20,Repeated 2 Times
Number=100,Repeated 1 Times
Number=10,Repeated 2 Times
Number=30,Repeated 2 Times

No comments:

Post a Comment