Click here to Skip to main content
15,915,081 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
I have two dictionaries D1 and D2 as follows
VB
Dim D1 As New Dictionary(Of String, String)
Dim D2 As New Dictionary(Of String, String)

I want to combine these two dictionaries into one new dictionary as follows:
VB
Dim D3 As New Dictionary(Of String, String)
D3 = D1.Union(D2)

But I get error! Any help? Notice that there is no duplicate in the keys

What I have tried:

I can find many examples but for C# not for VB.net
Posted
Updated 20-Nov-16 22:31pm
v2
Comments
Afzaal Ahmad Zeeshan 21-Nov-16 3:48am    
What error?

Union does not return a Dictionary, it returns an IEnumerable.
If you need a Dictionary, you need to use ToDictionary to convert it:
VB
Dim D1 As New Dictionary(Of String, String)()
Dim D2 As New Dictionary(Of String, String)()
...
Dim D3 As Dictionary(Of String, String) = D1.Union(D2).ToDictionary(Function(p) p.Key, Function(p) p.Value)
 
Share this answer
 
Comments
Andy Lanng 21-Nov-16 4:33am    
Dammit Griff! Always beat me by seconds :Þ
OriginalGriff 21-Nov-16 4:43am    
Sorry! Have an upvote as compensation!
Andy Lanng 21-Nov-16 8:33am    
^_^
The linq extensions work on IEnumerable objects. A dictionary is IEnumerable<keyvaluepair>. It will also return the IEnumerable type.

This being the case, you need to create a dictionary out of the ienumerable. Fortunatly, there is an extension for this, too.

Enumerable.ToDictionary(TSource, TKey) Method (IEnumerable(TSource), Func(TSource, TKey)) (System.Linq)[^]

C#:
C#
D3 = D1.Union(D2).ToDictionary(d=>d.Key, d=>d.Value)


VB:
VB
D3 = D1.Union(D2).ToDictionary(Function(d) d.Key, Function(d) d.Value)


Hope that helps ^_^
Andy
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900