在 C# 中合并字典,以便存在公共键
Merging dictionaries in C# such that common keys are present
我有两个字典。
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");
我希望得到一个字典,这样只有 DictA 的元组存在,它们具有与 testDict
中相同的键
因此示例合并字典应如下所示:
Dictionary<string, string> DictMerged = new Dictionary<string, string>();
DictMerged.Add("Name", "Sarah");
我希望我已经能够解释我的要求..
真诚感谢任何帮助
谢谢
一种可能的方式:
var DictMerged = DictA.Where(o => testDict.ContainsKey(o.Key))
.ToDictionary(o => o.Key, o => o.Value);
上面的代码只是过滤DictA
中的itemes,其中item key存在于testDict
个keys中,然后将结果投影到一个新的字典实例中。
你可以用 LINQ
:
var resultDict = testDict.Keys.Intersect(DictA.Keys)
.ToDictionary(t => t, t => DictA[t]);
您可以在两个词典之间进行连接。像这样的东西(在这里输入,所以它可能有点偏离):
dictA
.Join(testDict, kv => kv.Key, kv => kv.Key, (kva, kvt) => kva)
.ToDictionary(kv => kv.Key, kv => kv.Value)
这就像数据库中两个表之间的连接一样。第二个和第三个参数是说你想在每个字典的键上加入(每一边的处理方式相同)。最后一个参数说 "for each match, select the key-value item from DictA (and discard the one from testDict)" 并最终将弹出的 KeyValuePairs 序列转换回字典形式。
我有两个字典。
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");
我希望得到一个字典,这样只有 DictA 的元组存在,它们具有与 testDict
中相同的键因此示例合并字典应如下所示:
Dictionary<string, string> DictMerged = new Dictionary<string, string>();
DictMerged.Add("Name", "Sarah");
我希望我已经能够解释我的要求..
真诚感谢任何帮助
谢谢
一种可能的方式:
var DictMerged = DictA.Where(o => testDict.ContainsKey(o.Key))
.ToDictionary(o => o.Key, o => o.Value);
上面的代码只是过滤DictA
中的itemes,其中item key存在于testDict
个keys中,然后将结果投影到一个新的字典实例中。
你可以用 LINQ
:
var resultDict = testDict.Keys.Intersect(DictA.Keys)
.ToDictionary(t => t, t => DictA[t]);
您可以在两个词典之间进行连接。像这样的东西(在这里输入,所以它可能有点偏离):
dictA
.Join(testDict, kv => kv.Key, kv => kv.Key, (kva, kvt) => kva)
.ToDictionary(kv => kv.Key, kv => kv.Value)
这就像数据库中两个表之间的连接一样。第二个和第三个参数是说你想在每个字典的键上加入(每一边的处理方式相同)。最后一个参数说 "for each match, select the key-value item from DictA (and discard the one from testDict)" 并最终将弹出的 KeyValuePairs 序列转换回字典形式。