C#中如何查找Dictionary中的重复值

简介

在这篇帮助文档中,我将向你展示如何实现c#里字典中重复值的查找。你知道的对于一个老鸟来说,这是非常简单的代码。但是尽管如此,这也是一篇对c#初学者非常有用的帮助文档。

背景

多数程序员对小型数据源存储的处理方式通常是创建字典进行键值存储。主键时唯一的,但是字典值却可能有重复的元素。

代码

这里我使用了一个简单的LINQ语句来查找字典中的重复值。

 代码如下 复制代码
//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.111cn.net </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 />");
}
 

 

更多详细内容请查看:http://www.111cn.net/net/160/56736.htm

posted @ 2014-01-15 09:20  divor  阅读(6770)  评论(0编辑  收藏  举报