合并两个字典对c#not pure concat

Arn*_*nab 1 .net c# linq 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");
Run Code Online (Sandbox Code Playgroud)

我希望得到一个字典,以便testDict的键存在,并且存在DictA中存在的那些键的值.

因此合并字典的示例应如下所示:

Dictionary<string, string> DictMerged = new Dictionary<string, string>();
                DictMerged.Add("Name", "Sarah");
                DictMerged.Add("City", "NY");
Run Code Online (Sandbox Code Playgroud)

我希望我能够解释我的要求..

我试过了..

testDict.Concat(DictA)
  .GroupBy(kvp => kvp.Key, kvp => kvp.Value)
  .ToDictionary(g => g.Key, g => g.Last());
Run Code Online (Sandbox Code Playgroud)

但这给了我DictA'State',我不想要......

任何帮助都是真诚的感谢

谢谢

Hos*_*Rad 5

我想你正在寻找这个:

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

// result:
// {"Name", "Sarah"}
// {"City", "NY"}
Run Code Online (Sandbox Code Playgroud)