Tuesday 12 August 2014

Find duplicate value in List (lambda expression/group-by )

Here i am going to explain how we can find the duplicate count in list as so many time interviewer ask this program to candidates specially freshers. 

Lambda expression:
A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. Lambda expressions are particularly helpful for writing LINQ query expressions.
To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator =>, and you put the expression or statement block on the other side. For example, the lambda expression x => x * x specifies a parameter that’s named x and returns the value of x squared. You can assign this expression to a delegate type.
GroupBy :
transforms a collection into groups. Each group has a key. With this method from the System.Linq namespace, you can do this in your C# program on many collections. We examine the GroupBy method on a collection of numbers.

  public void findDuplicate()
            {
                int[] i = new int[] { 1, 2, 4, 2, 3, 65, 7, 8, 56, 45, 34, 3, 3, 3, 3, 3, 4,                                       4, 4, 5, 5, 1, 2 };
                var m = i.GroupBy(x => x);
                foreach (var item in m)
                {
                    Console.WriteLine("values {0}, repeated {1}", item.Key, item.Count());
                }
            }




output : 


No comments:

Post a Comment