如何将HashTable转换为C#中的字典?可能吗?例如,如果我有HashTable中的对象集合,并且如果我想将它转换为具有特定类型的对象的字典,那么该怎么做?将HashTable转换为C#中的字典#
32
A
回答
53
public static Dictionary<K,V> HashtableToDictionary<K,V> (Hashtable table)
{
return table
.Cast<DictionaryEntry>()
.ToDictionary (kvp => (K)kvp.Key, kvp => (V)kvp.Value);
}
+0
感谢您转换为字典并将键和值转换为给定类型的完整答案。 – RKP
8
var table = new Hashtable();
table.Add(1, "a");
table.Add(2, "b");
table.Add(3, "c");
var dict = table.Cast<DictionaryEntry>().ToDictionary(d => d.Key, d => d.Value);
+2
的遗留应用程序,谢谢你的解决方案,它不需要循环,这正是我正在寻找的。然而,我接受另一个解决方案作为答案,因为它会执行更正类型的转换,并为其定义扩展方法。上面的那个返回key和value的通用对象类型,这与hashtable没有任何其他的优势。 – RKP
3
你也可以创建代理-J的回答是
Dictionary<KeyType, ItemType> d = new Dictionary<KeyType, ItemType>();
foreach (var key in hashtable.Keys)
{
d.Add((KeyType)key, (ItemType)hashtable[key]);
}
0
Hashtable openWith = new Hashtable();
Dictionary<string, string> dictionary = new Dictionary<string, string>();
// Add some elements to the hash table. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
foreach (string key in openWith.Keys)
{
dictionary.Add(key, openWith[key].ToString());
}
2
扩展方法版本的扩展方法:
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public static class Extensions {
public static Dictionary<K,V> ToDictionary<K,V> (this Hashtable table)
{
return table
.Cast<DictionaryEntry>()
.ToDictionary (kvp => (K)kvp.Key, kvp => (V)kvp.Value);
}
}
相关问题
- 1. VB.NET:将Hashtable转换为具有通用值类型的字典
- 2. 将Hashtable转换为System.Version
- 3. 将DataTable转换为字典C#
- 4. 将NetworkX MultiDiGraph转换为字典或从字典中转换
- 5. 将字典列表转换为字典
- 6. 将字典转换为字典
- 7. 将字典输入转换为字典
- 8. 将字典转换为ArrayList
- 9. 将字典转换为HashEntry
- 10. 将类转换为字典
- 11. 将字典转换为XML
- 12. 将字典转换为OrderedDict
- 13. 将jSon转换为字典
- 14. 将字典转换为JSOn
- 15. 字典/ C++中的HashTable对象?
- 16. 将Json转换为Python中的字典
- 17. 如何将列表<object>转换为C#中的Hashtable?
- 18. 在Python中将字典转换为JSON
- 19. 在swift2中将NSDictionary转换为字典
- 20. C#字符串转换为字典
- 21. 如何在C#中将Dictionary <>转换为Hashtable?
- 22. 如何将csv转换为Python中字典的字典?
- 23. 将列表转换为Python中的字典字典
- 24. 如何将数组转换为字典中的目标c
- 25. 将字典转换为C#中的列表集合
- 26. 如何使用C#中的LINQ将字典转换为SortedDictionary?
- 27. 如何将一列列表转换为C#中的字典?
- 28. 将Hashtable转换为对象列表
- 29. 如何将NameValueCollection转换为Hashtable
- 30. 将F#映射转换为Hashtable
你知道的类型编译时或运行时的'Dictionary'元素? –
HashTable的所有对象(键和值)都可以转换为将用作Dictionary的通用参数的特定目标类型?或者你是否愿意排除HashTable中不适合的类型? – daveaglick
如果可能的话,你应该把对象放在一个'Dictionary'开始。 'HashTable'类自从引入'Dictionary'后实际上已经过时了。由于'Dictionary'是'HashTable'的通用替代品,因此代码需要稍微调整以使用'Dictionary'代替。 – Guffa