Merge two dictionaries by key but keep both values

时间:2018-01-23 19:25:48

标签: vb.net dictionary merge

I have 2 dictionaries:

Dim dict1 As New Dictionary(Of String, String)
dict1.Add("first","A")
dict1.Add("third","C")
dict1.Add("fifth","E")
dict1.Add("sixth","F")

Dim dict2 As New Dictionary(Of String, String)
dict2.Add("first","AA")
dict2.Add("second","BB")
dict2.Add("fourth","DD")
dict2.Add("sixth","FF")

I want to combine them into one master list by key, retaining both values. My final result would be in the format:

Dim combined As Dictionary(Of String, List(of String))

And based on the example above, would look something like:

{
    "first" : ["A", "AA"],
    "second" : ["", "BB"],
    "third" : ["C", ""],
    "fourth" : ["", "DD"],
    "fifth" : ["E", ""],
    "sixth" : ["F", "FF"]
}

Notice that every key from both lists carries over to the new, combined list. If the key has a value in both locations, both values are put into the list. If the key has a value in only one of the two locations, the value is placed in the corresponding first or second position with an empty string in the other.

How could I merge them in this manner?

1 个答案:

答案 0 :(得分:0)

I recommend a Tuple(Of String, String). Item1 will be the first one and Item2 will be the second dictionary. Since you know the list would be exactly two, you might as well do it this way instead.

Dim combined As New Dictionary(Of String, Tuple(Of String, String))
For Each key as String in dict1.Keys.Union(dict2.Keys)

    Dim value1 as String = "" : dict1.TryGetValue(key, value1)
    Dim value2 as String = "" : dict2.TryGetValue(key, value2)
    combined.Add(key, new Tuple(Of String, String)(value1, value2))
Next

If you want the list, the question will be if you want the elements if they don't exist.

Dim combined As New Dictionary(Of String, List(Of String))
For Each key as String in dict1.Keys.Union(dict2.Keys)

    Dim value1 as String = ""
    Dim keyAdded as Boolean = False
    Dim keyList as new List(Of String)
    If dict1.TryGetValue(key, value1) Then 
      keyList.Add(value1)
    End If
    Dim value2 as String = ""
    If dict2.TryGetValue(key, value2) Then
        keyList.Add(value2)
    End If
    combined.Add(key, keyList)
Next