C# Find Duplicate Array Values
Use LINQ GroupBy to count how many times each value appears in an integer array.
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.