I’ve two dictionaries as following:
//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");
I need to compare above two dictionaries using LINQ query with condition:
-
All keys in dict2 should match with keys in dict1
-
The matched keys should have equivalent value
I tried creating a extension method on dictionary, but it returns false as dict1 contains one extra pair.
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]});
}
}
You can just use the
All()extension method to test if all elements of a collection satisfy a certain condition.Another (probably faster, but not so funky) approach is to do the intersection of two hashsets: