Arnab
Arnab

Reputation: 2354

Merging two dictionary pairs c# not pure concat

I have two Dictionary.

Dictionary<string, string> testDict = new Dictionary<string, string>();
            testDict.Add("Name", "John");
            testDict.Add("City", "NY");

Dictionary<string, string> DictA = new Dictionary<string, string>();
            DictA.Add("Name", "Sarah");
            DictA.Add("State", "ON");

I wish to get a Dictionary such that the keys of testDict are present and the values of those keys present in DictA are present.

So the example merged dictionary should look as below:

Dictionary<string, string> DictMerged = new Dictionary<string, string>();
                DictMerged.Add("Name", "Sarah");
                DictMerged.Add("City", "NY");

I hope I have been able to explain my requirements..

I tried..

testDict.Concat(DictA)
  .GroupBy(kvp => kvp.Key, kvp => kvp.Value)
  .ToDictionary(g => g.Key, g => g.Last());

But this gave me DictA 'State' as well which I do not want..

Any help is sincerely appreciated

Thanks

Upvotes: 1

Views: 344

Answers (3)

juharr
juharr

Reputation: 32286

If you have the GetOrDefault extension method defined here

Then you can do

var result = testDict.ToDictionary(
    kvp => kvp.Key, 
    kvp => DictA.GetOrDefault(kvp.Key, kvp.Value));

The difference between this and using DictA.ContainsKey(kvp.Key) ? DictA[kvp.Key] : i.Value is that there is only one lookup done on DictA versus two when the key is present.

Upvotes: 2

austin wernli
austin wernli

Reputation: 1801

This would work

        var testDict = new Dictionary<string, string> { { "Name", "John" }, { "City", "NY" } };
        var DictA = new Dictionary<string, string> { { "Name", "Sarah" }, { "State", "ON" } };
        var mergedDict = testDict.ToDictionary(keyVal => keyVal.Key, keyVal => DictA.ContainsKey(keyVal.Key) ? DictA[keyVal.Key] : keyVal.Value);

Upvotes: 0

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32481

I think you are looking for this:

var result = 
    testDict.ToDictionary(
             i => i.Key, 
             i => DictA.ContainsKey(i.Key) ? DictA[i.Key] : i.Value);

// result:
// {"Name", "Sarah"}
// {"City", "NY"}

Upvotes: 5

Related Questions