[英]Compare two dictionaries (Dictionary<string, List<string>>)
[英]Validate and Compare between two dictionaries when both Dictionaries value contains List like "Dictionary<string, List<string>>"
嗨,兩個通用詞典如下語法格式
Dictionary<string, List<string>> Test1 = new Dictionary<string, List<string>>(); Dictionary<string, List<string>> Test2 = new Dictionary<string, List<string>>();
現在我需要比較和驗證這兩個字典
樣本數據會像
示例 1
測試1
細繩 | 列表 |
---|---|
一個 | 蘋果、香蕉 |
乙 | 葡萄、梨 |
C | 橙子、櫻桃 |
測試2
細繩 | 列表 |
---|---|
一個 | 蘋果、香蕉、西瓜 |
乙 | 葡萄、梨 |
C | 橙子、櫻桃 |
這個上面的例子應該被驗證並發現 test1 不包含在 Test2
示例 2
測試3
細繩 | 列表 |
---|---|
一個 | 蘋果、香蕉 |
乙 | 葡萄、梨 |
C | 橙子、櫻桃 |
測試4
細繩 | 列表 |
---|---|
一個 | 蘋果、香蕉 |
乙 | 葡萄、梨 |
C | 橙子、櫻桃 |
D | 芒果、菠蘿、李子 |
應該驗證上面的這個例子,並發現 test3 包含在 Test4 中
請注意,如果List<>
中的字符串順序不重要,請考慮使用HashSet<>
而不是List<>
。 下面的代碼做我認為你想要的......
static bool List1IsSubsetOfList2(List<string> list1, List<string> list2)
{
return !list1.Except(list2).Any();
}
static bool List1ContentsSameAsList2(List<string> list1, List<string> list2)
{
// if order is relevant do not sort
list1.Sort();
list2.Sort();
// same entry values in same order
return list1.SequenceEqual(list2);
}
static bool Dictionary1SubsetDictionary2(Dictionary<string, List<string>> dict1, Dictionary<string, List<string>> dict2)
{
var k1 = dict1.Keys.ToList();
var k2 = dict2.Keys.ToList();
var fKeys = List1IsSubsetOfList2(k1, k2);
return fKeys && k1.All(k => List1ContentsSameAsList2(dict1[k], dict2[k]));
}
var test1 = new Dictionary<string, List<string>>
{
{ "A", new List<string> { "Apple", "Banana" } }
,{ "B", new List<string> { "Grape", "Pears" } }
,{ "C", new List<string> { "Orange", "Cherry" } }
};
var test2 = new Dictionary<string, List<string>>
{
{ "A", new List<string> { "Apple", "Banana", "Watermelon" } }
,{ "B", new List<string> { "Grape", "Pears" } }
,{ "C", new List<string> { "Orange", "Cherry" } }
};
var test3 = test1;
var test4 = new Dictionary<string, List<string>>
{
{ "A", new List<string> { "Apple", "Banana" } }
,{ "B", new List<string> { "Grape", "Pears" } }
,{ "C", new List<string> { "Orange", "Cherry" } }
,{ "D", new List<string> { "Mango", "Pineapple", "Plum" } }
};
Console.WriteLine($"Test1 is contained in Test2 {Dictionary1SubsetDictionary2(test1,test2)}");
Console.WriteLine($"Test2 is contained in Test1 {Dictionary1SubsetDictionary2(test2,test1)}");
Console.WriteLine($"Test3 is contained in Test4 {Dictionary1SubsetDictionary2(test3,test4)}");
Console.WriteLine($"Test4 is contained in Test3 {Dictionary1SubsetDictionary2(test4,test3)}");
結果
Test1 is contained in Test2 False
Test2 is contained in Test1 False
Test3 is contained in Test4 True
Test4 is contained in Test3 False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.