convert HashTable to Dictionary in C#

旧巷老猫 提交于 2019-11-27 21:06:06

问题


how to convert a HashTable to Dictionary in C#? is it possible? for example if I have collection of objects in HashTable and if I want to convert it to a dictionary of objects with a specific type, how to do that?


回答1:


public static Dictionary<K,V> HashtableToDictionary<K,V> (Hashtable table)
{
   return table
     .Cast<DictionaryEntry> ()
     .ToDictionary (kvp => (K)kvp.Key, kvp => (V)kvp.Value);
}



回答2:


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);



回答3:


also you can create an extension method for that

Dictionary<KeyType, ItemType> d = new Dictionary<KeyType, ItemType>();
foreach (var key in hashtable.Keys)
{
 d.Add((KeyType)key, (ItemType)hashtable[key]);
}



回答4:


Extension method version of agent-j's answer:

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);
    }
}



回答5:


    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());
    }


来源:https://stackoverflow.com/questions/6455822/convert-hashtable-to-dictionary-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!