Using LINQ To Find Duplicates

by jason3. February 2010 20:16

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.

Tags:

Development | LINQ

About

Jason Williams is a .NET developer in Lincoln, Nebraska.

The name "Centrolutions" came out of a long search for a domain name. The goal was to create a name that conveyed an ideology of writing software centered (Centr--) on a solution (--olutions) for a particular problem. In other words, it was the only name in a long list that wasn't already registered on the internet.

If you're looking for the products I have for sale, you should go here.