epv epv - 1 month ago 7
C# Question

Comparing two Key Value Dictionaries C#

I have two dictionaries

1 has the Dictionary A (expected values) and Dictionary B.

They are both dictionaries, and I want to be able to say, if B.Keys contains a key from A, compare the two values and return true or false.

How do I write something like this:

if (B.ContainsKey(A.Keys))
{

}


Example of Key Value:

Dictionary<Key, Value> B = {name, "valueb"; last, "smith"}
Dictionary<Key, Value> A = {name, "valuea"; last, "smith"; middle, "m"}

if (name == name)
{
if("valueb" == "valuea" )
{
return false;
}
}

Answer Source

Scan one dictionary and lookup in second and compare like this:

var a = new Dictionary<TK,TV>();
var b = new Dictionary<TK,TV>();

var isEquals = a.All(x =>
{
    TV v;
    if (b.TryGetValue(x.Key, out v))
       return x.Value.Equals(v);

    return false;
});

UPD

isEquals = true;
foreach(x in a)
{
    TV v;
    if (b.TryGetValue(x.Key, out v))
       isEquals = isEquals && x.Value.Equals(v);
    else
    {
       isEquals = false;
       break;
    }

}