怎样才能在字典列表中找到重复的字典。我知道如何比较两本字典,但如何循环?
List<Dictionary<string, string>> allLists = new List<Dictionary<string, string>>();
foreach (Dictionary<string, string> allList in allLists)
{
}在比较两本字典时,您就是这样做的,我希望能够做类似于字典列表的工作:
public static void CompareDict()
{
Dictionary<string, object> dic1 = new Dictionary<string, object>();
Dictionary<string, object> dic2 = new Dictionary<string, object>();
dic1.Add("Key1", new { Name = "abc", Number = "123", Address = "def", Loc = "xyz" });
dic1.Add("Key2", new { Name = "DEF", Number = "123", Address = "def", Loc = "xyz" });
dic1.Add("Key3", new { Name = "GHI", Number = "123", Address = "def", Loc = "xyz" });
dic1.Add("Key4", new { Name = "JKL", Number = "123", Address = "def", Loc = "xyz" });
dic2.Add("Key1", new { Name = "abc", Number = "123", Address = "def", Loc = "xyz" });
dic2.Add("Key2", new { Name = "DEF", Number = "123", Address = "def", Loc = "xyz" });
dic2.Add("Key3", new { Name = "GHI", Number = "123", Address = "def", Loc = "xyz" });
dic2.Add("Key4", new { Name = "JKL", Number = "123", Address = "def", Loc = "xyz" });
bool result = dic1.SequenceEqual(dic2);
Console.WriteLine(result);
}发布于 2020-10-30 12:15:30
最干净的方法可能是创建一个通用字典均等化比较器:
public class DictionaryComparer<TKey, TValue> :
IEqualityComparer<IDictionary<TKey, TValue>>
{
public bool Equals(IDictionary<TKey, TValue> x, IDictionary<TKey, TValue> y)
{
return Enumerable.SequenceEqual(x, y);
}
public int GetHashCode(IDictionary<TKey, TValue> d)
{
var hash = default(KeyValuePair<TKey, TValue>).GetHashCode();
foreach (var kp in d)
hash ^= kp.GetHashCode();
return hash;
}
}现在,您可以对字典进行分组,以检查副本:
var hasDups = allLists.GroupBy(d => d, new DictionaryComparer<string, string>())
.Where(g => g.Count() > 1)
.Any();发布于 2021-11-19 11:50:13
dict1 ={ "employee" : [{"name": "employee1", "id":1234},
{"name": "employee2" ,"id":2345},
{"name": "employee3", "id":3456},
{"name": "employee4" ,"id":4567}]
}
dict2 ={ "employee" : [{"name": "employee4" ,"id":4567},
{"name": "employee2" ,"id":2345},
{"name": "employee3", "id":3456},
{"name": "employee1" ,"id":1234}]
}
print("equal",dict1==dict2)
print (dict1,dict2)
print (dict1.keys())
print (dict2.keys())
print("*****",dict1.items())
for i,j in dict1.items():
len1 = len(j)
for k,l in dict2.items():
len2 = len(l)
if i == k:
print ("keys are same")
if len1==len2:
for m in range(len1):
print("OOO",dict1[i][m].items())
for a,b in dict1[i][m].items():
for c,d in dict2[k][m].items():
if a == c and b==d:
print("same")
else :
pass
else:
print ("keys are different")
break
In this code checking for similar dictionaries having list of dictionaries.https://stackoverflow.com/questions/64607128
复制相似问题