List中每组Dictionary包含多个key,其中hash可能在list中包含重复值,
怎么去重?
比如:
dict1.add("hash","111");
dict1.add("a","222");
dict2.add("hash","111");
dict2.add("a","333");
dict3.add("hash","222");
dict3.add("a","333");
list.add(dict1);
list.add(dict2);
list.add(dict3);
其中hash值是111的,我只想保留一个,也就是list中,去重后,保留dict1(或者dict2)和ditc3即可
或者有更好的集合去处理这种需求?
给你:
static void Main(string[] args)
{
Dictionary<string, string> dict1 = new Dictionary<string, string>();
dict1.Add("hash", "111");
dict1.Add("a", "222");
Dictionary<string, string> dict2 = new Dictionary<string, string>();
dict2.Add("hash", "111");
dict2.Add("a", "333");
Dictionary<string, string> dict3 = new Dictionary<string, string>();
dict3.Add("hash", "222");
dict3.Add("a", "333");
List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
AddDict(dict1, list);
AddDict(dict2, list);
AddDict(dict3, list);
Console.ReadKey();
}
private static void AddDict(Dictionary<string, string> dict, List<Dictionary<string, string>> list)
{
Dictionary<string, string> temp;
foreach (var item in dict)
{
bool isAdd = true;
var query = list.Select(l => l.Keys.Contains(item.Key) && l.Values.Contains(item.Value)).ToList();//匹配键和值
for (int i = 0; i < query.Count; i++)//遍历每一个匹配结果
{
if (query[i])//如果存在,结果为true
{
isAdd = false;
break;
}
}
if (isAdd)
{
temp = new Dictionary<string, string>();
temp.Add(item.Key, item.Value);
list.Add(temp);
}
}
}