Question: I currently have 2 dictionaries with ard 30,000keys.

I am currently using two foreach loops to find the unique keys in dict1. And I write the unique keys in dict2 to another dictionary(3). 

If the keys match i perform a check to see if the value are the same. And print if they are not the same.

Is it better to use foreach, it seems to be affecting the performance. Is there any other faster solution or built in functions? Ir shd I try the dict.contains method.

---

```
Dict1                    Dict2

Keys    Values           Keys     Values        
S0111   00000            S0000    00010
S0000   00010            S0020    00015
S0020   00015            S0040    00150
S0040   00200            S0050    00250

```

---

```
        foreach (KeyValuePair<string, string> sourceRow in sourceData)
        {
            foreach (KeyValuePair<string, string> dumpRow in dumpData)
            {
                // A in C, skip
                if (sourceRow.Key == dumpRow.Key)
                {
                    Is_Unique_Address = false;

                    if (sourceRow.Value != dumpRow.Value)
                    {
                        Data_Mismatch_Criteria(sourceRow.Key, sourceRow.Value, dumpRow.Key, dumpRow.Value);
                    }

                }
            }
        }

```

Answer: 
```
foreach (KeyValuePair<string, string> sourceRow in sourceData)
{
    string dumpValue;

    if (dumpData.TryGetValue(sourceRow.Key, out dumpValue) && dumpValue != sourceRow.Value)
    {
        Data_Mismatch_Criteria(sourceRow.Key, sourceRow.Value, sourceRow.Key, dumpValue);
    }
}

```
Well, this LINQ query will return dictionary of records that either are not presented in both dictionaries or has different values :

```
var dictOfUniqueValues =
     dict1.Where(kv => !dict2.ContainsKey(kv.Key)).Concat(
         dict2.Where(kv => !dict1.ContainsKey(kv.Key) || dict1[kv.Key] != kv.Value))
    .ToDictionary(kv => kv.Key, kv => kv.Value);

```

Well let's take a closer look of what's going on here : 

```
var dictOfUniqueValues =

     // get records from dict1 that don't exist in dict2 by comparing keys
     dict1.Where(kv => !dict2.ContainsKey(kv.Key)).Concat(

     // get records from dict2 that don't exist in dict1 by comparing keys
     // and records that do exist, but values are not equal
         dict2.Where(kv => !dict1.ContainsKey(kv.Key) || dict1[kv.Key] != kv.Value))

     // convert the resulting IEnumerable<KeyValuePair<T1, T2>> to dictionary
    .ToDictionary(kv => kv.Key, kv => kv.Value);

```