Friday, July 25, 2008

How to find duplicate values from List<> ?

     I have generic list say, List<int> and I want to find the duplicate values from the List<int> and store it in new List<int>. There are many ways to achive this. One can loop through all the elements of List<int> and store the duplicate in other list OR can use anonymous method to acieve same. I love the anonymous method. Here is the code to get duplicate value from List<>.

   1: List<int> lstVals = new List<int>();
   2: lstVals.Add(1);
   3: lstVals.Add(2);
   4: lstVals.Add(1);
   5: lstVals.Add(4);
   6: lstVals.Add(5);
   7: lstVals.Add(6);
   8: lstVals.Add(4);
   9: lstVals.Add(1);
  10:  
  11: List<int> lstVals1 = lstVals.FindAll(delegate(int i)
  12:                      {
  13:                            return lstVals.FindAll(delegate(int j) 
  14:                                   { 
  15:                                      return j == i; 
  16:                                   }).Count() > 1;
  17:                      }).Distinct().ToList();

Happy Programming !!!!

No comments: