如何组合两个词典 [英] How do I combine two dictionaries

查看:132
本文介绍了如何组合两个词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个词典D1和D2如下

I have two dictionaries D1 and D2 as follows

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:

Dim D3 As New Dictionary(Of String, String)
D3 = D1.Union(D2)



但我收到错误!有帮助吗?请注意,按键没有重复



我尝试过:



我可以找到很多例子但是对于C#而不是VB.net


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

推荐答案

Union不返回一个字典,它返回一个IEnumerable。

如果你需要一个字典,你需要使用ToDictionary来转换它:

Union does not return a Dictionary, it returns an IEnumerable.
If you need a Dictionary, you need to use ToDictionary to convert it:
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)


linq扩展适用于IEnumerable对象。字典是IEnumerable< keyvaluepair>。它还将返回IEnumerable类型。



在这种情况下,您需要创建一个不可数的字典。幸运的是,这也有一个扩展。



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



C#:

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#:
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)





希望有所帮助^ _ ^

Andy



Hope that helps ^_^
Andy


这篇关于如何组合两个词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆