Подтвердить что ты не робот

Конвертировать HashTable в словарь в С#

как преобразовать HashTable в словарь в С#? Является ли это возможным? например, если у меня есть коллекция объектов в HashTable, и если я хочу преобразовать ее в словарь объектов с определенным типом, как это сделать?

4b9b3361

Ответ 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

также вы можете создать метод расширения для этого

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

Ответ 4

Версия метода расширения-agent-j:

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