【问题标题】:Convert HashTable to Dictionary in C#在 C# 中将 HashTable 转换为字典
【发布时间】:2011-09-21 07:11:40
【问题描述】:

如何在 C# 中将 HashTable 转换为 Dictionary?有可能吗?

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

【问题讨论】:

  • 你知道Dictionary元素在编译时或运行时的类型吗?
  • HashTable 的所有对象(键和值)是否都可以转换为将用作字典的通用参数的特定目标类型?还是您宁愿排除 HashTable 中不属于适当类型的那些?
  • 如果可能,您应该将对象放在Dictionary 中开始。自从引入了 Dictionary 以来,HashTable 类实际上已经过时了。由于DictionaryHashTable 的通用替代品,因此您的代码需要稍作调整才能改用Dictionary
  • 类型在编译时是已知的,Hashtable 中的所有对象都是同一类型。我正在开发一个使用哈希表的遗留应用程序

标签: c# .net generics dictionary hashtable


【解决方案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】:

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

【讨论】:

    【解决方案4】:

    您可以为此创建扩展方法

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

    【讨论】:

      【解决方案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());
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-15
        • 1970-01-01
        • 1970-01-01
        • 2010-09-23
        • 2013-11-11
        • 1970-01-01
        • 1970-01-01
        • 2013-07-18
        相关资源
        最近更新 更多