Skip to content
Amal Hashim
All posts
Snippet

C# Find Duplicate Array Values

Use LINQ GroupBy to count how many times each value appears in an integer array.

1 min read#.NET#C#

This function shows the power of LINQ. It groups the array items and returns a dictionary of each value and how many times it appears.

csharp
private Dictionary<int, int> GetArrayDuplicates(int[] arrayToSearch)
{
   Dictionary<int, int> counts = arrayToSearch.GroupBy(arrayItem => arrayItem)
      .ToDictionary(groupedItem => groupedItem.Key,
      groupedItem => groupedItem.Count());
   return counts;
}

Example

csharp
int[] array = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 80, 40, 50, 100 };
Dictionary<int, int> counts = GetArrayDuplicates(array);

The values 40, 50, 80 and 100 each have a count of 2. Every other value has a count of 1. Filter on Value > 1 to keep only the duplicates.