Introduction
In this tip I will show you how to find dictionary duplicate values in C#. An expert you know this is very simple code, but nonetheless it is a very useful tip for many beginners in C#.
Background
Programmers like to create a dictionary for small data source to store key value type data. Keys are unique, but dictionary values may be duplicates.
Using the code
Here I use a simple LINQ statement to find duplicate values from dictionary.
Dictionary<int, string> plants = new Dictionary<int, string>() {
{1,"Speckled Alder"},
{2,"Apple of Sodom"},
{3,"Hairy Bittercress"},
{4,"Pennsylvania Blackberry"},
{5,"Apple of Sodom"},
{6,"Water Birch"},
{7,"Meadow Cabbage"},
{8,"Water Birch"}
};
Response.Write("<b>dictionary elements........</b><br />");
foreach (KeyValuePair<int, string> pair in plants)
{
Response.Write(pair.Key + "....."+ pair.Value+"<br />");
}
var duplicateValues = plants.GroupBy(x => x.Value).Where(x => x.Count() > 1);
Response.Write("<br /><b>dictionary duplicate values..........</b><br />");
foreach(var item in duplicateValues)
{
Response.Write(item.Key+"<br />");
}