Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to find dictionary duplicate values in C#

0.00/5 (No votes)
29 Dec 2013 1  
It is very simple and useful tip to find duplicate values from a dictionary.

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.

C#
//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"}    
};  
  
Response.Write("<b>dictionary elements........</b><br />");
        
//loop dictionary all elements   
foreach (KeyValuePair<int, string> pair in plants)  
{
    Response.Write(pair.Key + "....."+ pair.Value+"<br />");
}  
  
//find dictionary duplicate values.  
var duplicateValues = plants.GroupBy(x => x.Value).Where(x => x.Count() > 1);

Response.Write("<br /><b>dictionary duplicate values..........</b><br />");

//loop dictionary duplicate values only            
foreach(var item in duplicateValues)  
{
    Response.Write(item.Key+"<br />");
}   

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here