Method in C to find duplicate values in Dictionary
- 2020-06-03 08:07:20
- OfStack
Introduction to the
In this help document, I'll show you how to implement the lookup of repeated values in the dictionary in c#. You know this is very simple code for an old bird. Nevertheless, this is a very useful help document for beginners in c#.
background
The way most programmers deal with small data source stores is usually to create dictionaries for key-value stores. The primary key is only 1, but the dictionary value may have duplicate elements.
code
Here I use a simple LINQ statement to find duplicate values in the 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........ www.ofstack.com </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 />");
}