SoFunction
Updated on 2025-03-08

Methods to find duplicate values ​​in Dictionary in C#

In this help document, I will show you how to implement the search for duplicate values ​​in dictionary in C#. You know, for an old bird, this is very simple code. But despite this, this is also a very useful help document for beginners in C#.
background: Most programmers usually handle small data source storage by creating dictionaries for key-value storage. Only when the primary key is, but the dictionary value may have duplicate elements.
The code is as follows

//initialize a dictionary with keys and values.  
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"}  
}; 
  
("<b>dictionary elements........  </b><br />");
     
//loop dictionary all elements  
foreach (KeyValuePair<int, string> pair in plants) 
{
  ( + "....."+ +"<br />");
} 
  
//find dictionary duplicate values. 
var duplicateValues = (x => ).Where(x => () > 1);
 
("<br /><b>dictionary duplicate values..........</b><br />");
 
//loop dictionary duplicate values only      
foreach(var item in duplicateValues) 
{
  (+"<br />");
}

The above is what I use to find duplicate values ​​in the dictionary. You can try experimenting.