簡介
在這篇幫助文檔中,我將向你展示如何實現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