Using LINQ To Find Duplicates


I recently ran into a situation that has come up plenty of times for plenty of people. I had an array of integers and I needed to figure out if any of the numbers were in the array more than once.

A variety of solutions ran through my head: sorting, looping, searching, etc. However, LINQ seemed like the most elegant solution. Here’s what I finally settled on:

var duplicates = activityIds.GroupBy(g => g)
      .Where(w => w.Count() > 1)
      .Select(s => s.Key);

if (duplicates.Count() > 0)
{
   errorMessage = "You may only register for a particular activity once";
   return false;
}

The first line simply groups the integers by their value. The second and third lines find and select every integer that appears in the array more than once (Count() > 1). In my case, I just needed to know if there were any duplicates, but you can see how you could easily list the duplicated values by iterating over the “duplicates” variable.

This same method can be used to find duplicates across any LINQ to objects – compatible collection and I’ll certainly be using it more in the future.