hegdesachin
hegdesachin

Reputation: 305

Custom compare dictionaries using LINQ

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:

  1. All keys in dict2 should match with keys in dict1

  2. 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]});
    }
}

Upvotes: 1

Views: 158

Answers (1)

sloth
sloth

Reputation: 101072

You can just use the All() extension method to test if all elements of a collection satisfy a certain condition.

var dict1 = new Dictionary<string, string>
{
    {"key1", "value1"},
    {"key2", "value2"},
    {"key3", "value3"}
};

var dict2 = new Dictionary<string, string>
{
    {"key1", "value1"},
    {"key2", "value2"}
};

dict2.All(kvp => dict1.Contains(kvp)); // returns true

Another (probably faster, but not so funky) approach is to do the intersection of two hashsets:

var h1 = new HashSet<KeyValuePair<string, string>>(dict1);
var h2 = new HashSet<KeyValuePair<string, string>>(dict2);
h1.IntersectWith(h2);
var result = (h1.Count == h2.Count); // contains true

Upvotes: 2

Related Questions