好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#中查找Dictionary中的重复值的方法

在这篇帮助文档中,我将向你展示如何实现c#里字典中重复值的查找。你知道的对于一个老鸟来说,这是非常简单的代码。但是尽管如此,这也是一篇对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........ www.zzvips.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 />" );

}

 以上就是我使用一个简单的LINQ语句来查找字典中的重复值,大家可以尝试实验一下。

dy("nrwz");

查看更多关于C#中查找Dictionary中的重复值的方法的详细内容...

  阅读:89次