65.9K
CodeProject is changing. Read more.
Home

How to find dictionary duplicate values in C#

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.05/5 (10 votes)

Dec 29, 2013

CPOL
viewsIcon

71856

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.

//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 />");
}