Friday, January 4, 2013

Check Duplicates in a ArrayList


ArrayList list = new ArrayList { 1, 9, 2, 1, 6, 5 };


Above is a array list of integers. We can use below methods to check the duplicates in the array list.

Method 1: Using the Contains method

private void AddItems(object o) 
 { 
  if(!list.Contains(o))
   { 
    list.Add(o); 
   }
 else
  {
   //Duplicate found
  } 
}

Method 2: Using LINQ

var x = from l in list.OfType() 
 group l by l into g 
 where g.Count() > 1 
 select g.Key; 

 if (x.Count() > 0) 
 { 
   // Duplicate found 
 }

No comments:
Write comments
Recommended Posts × +