我有两个字典如下:
//Dictionary 1:
Dictionary<string, string> dict1 = new Dictionary<string, string>();
dict1 .Add("key1", "value1");
dict1 .Add("key2", "value2");
dict1 .Add("key3", "value3");
//Dictionary 2 :
Dictionary<string, string> request = new Dictionary<string, string>();
request.Add("key1", "value1");
request.Add("key2", "value2");
我需要使用LINQ查询和条件来比较以上两个词典:
-
All keys in dict2 should match with keys in dict1
-
The matched keys should have equivalent value
我尝试在字典上创建一个扩展方法,但它返回false,因为dict1包含一个额外的对 .
public static class DictionaryExtension
{
public static bool CollectionEquals(this Dictionary<string, string> collection1,
Dictionary<string, string> collection2)
{
return collection1.ToKeyValue().SequenceEqual(collection2.ToKeyValue());
}
private static IEnumerable<object> ToKeyValue(this Dictionary<string, string> collection)
{
return collection.Keys.OrderBy(x => x).Select(x => new {Key = x, Value = collection[x]});
}
}
1 回答
您可以使用All()扩展方法来测试集合的所有元素是否满足特定条件 .
另一种(可能更快但不那么时髦)的方法是做两个哈希集的交集: