繁体   English   中英

在 C# 中将哈希表转换为字典

[英]Convert HashTable to Dictionary in C#

如何在 C# 中将哈希表转换为字典? 可能吗?

例如,如果我在 HashTable 中有一个对象集合,我想将它转换为具有特定类型的对象字典,我该怎么做?

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

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

您可以为此创建一个扩展方法

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM