Merge Two Dictionaries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
var d1 = new Dictionary<string, int> | |
{ | |
{ "a" , 1 }, | |
{ "b" , 2 } | |
}; | |
var d2 = new Dictionary<string, int> | |
{ | |
{ "c" , 3 } | |
}; | |
var d3 = GetMergedDict(d1, d2); | |
Console.WriteLine(d3); | |
} | |
public Dictionary<string, int> GetMergedDict(Dictionary<string, int> d1, Dictionary<string, int> d2) | |
{ | |
var mergedDict = new Dictionary<string, int>(); | |
var a = d1.Keys.ToArray(); | |
var b = d2.Keys.ToArray(); | |
for (int i = 0; i < a.Length; i++) | |
{ | |
if (!mergedDict.ContainsKey(a[i])) | |
mergedDict[a[i]] = d1[a[i]]; | |
else | |
mergedDict.Add(a[i], d1[a[i]]); | |
} | |
for (int j = 0; j < b.Length; j++) | |
{ | |
if (!mergedDict.ContainsKey(b[j])) | |
mergedDict[b[j]] = d2[b[j]]; | |
else | |
mergedDict.Add(b[j], d2[b[j]]); | |
} | |
return mergedDict; | |
} | |
// Define other methods and classes here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment