从一种类型转换字典到另一个 [英] Converting a Dictionary from one type to another

查看:139
本文介绍了从一种类型转换字典到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能转换词典(类型A中,类型B)词典(TypeC,键入) ?有转换时(假设第二词典字符串,字符串)的隐式转换,因此这个过程应该是自动的,对不对?我只是想不通一种优雅的方式来做到这一点。

How can I convert a Dictionary(Of TypeA, TypeB) to a Dictionary(Of TypeC, TypeD)? There is an implicit cast when converting (let's say the second dictionary is String, String), so this process should be automatic, right? I just can't figure out an elegant way to do this.

语言是VB.NET,但我可以读取并转换C#如果你更舒服。

The language is VB.NET, but I can read and convert C# if you're more comfortable with that.

推荐答案

我会使用Linq对这样的情况下。有一个 ToDictionary()方法将任何泛型IEnumerable(和词典< TA,TB> 是一个的IEnumerable< KeyValuePair< TA,TB>> )到字典采取可枚举元素的两个突出产生一个键和值的字典。这使得这些类型的转换非常简单:

I would use Linq for cases like this. There's a ToDictionary() method that converts any generic IEnumerable (and a Dictionary<TA,TB> is an IEnumerable<KeyValuePair<TA,TB>>) to a Dictionary by taking two projections of the Enumerable element to produce a key and value for the dictionary. It makes these kinds of conversions very simple:

Dictionary<TypeA, TypeB> myDictionary = new Dictionary<TypeA, TypeB>
                                            { 
                                               /*initialization here*/ 
                                            };
Dictionary<TypeC, TypeD> myChangedDictionary = 
    myDictionary.ToDictionary(x=>x.Key.AsTypeC(), x=>x.Value.AsTypeD())

AsTypeC()和AsTypeD()的占位符任何转换,需要从A / B到C / D去。你提出的第二个意思是词典&LT;字符串,字符串&GT; ;在这种情况下,你根本的ToString()两者的(如果你已经覆盖的方法),或使用键/值在某些的String.Format操作。

AsTypeC() and AsTypeD() are placeholders for whatever conversion is necessary to go from A/B to C/D. You suggested the second Dictionary was a Dictionary<string,string>; in that case you'd simply ToString() both of them (if you've overridden that method) or use the Key/Value in some String.Format operation.

这篇关于从一种类型转换字典到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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