【问题标题】:How to convert Dictionary<> to Hashtable in C#?如何在 C# 中将 Dictionary<> 转换为 Hashtable?
【发布时间】:2012-03-29 14:46:05
【问题描述】:

我看到很多关于如何将 Hashtable 转换为 Dictionary 的问题/答案,但是如何将 Dictionary 转换为 Hashtable?

【问题讨论】:

  • 你为什么需要它?哈希表非常具体,因为在键上计算的值会产生值的位置......而字典只是一个直接的(键,值)集合。为什么要将字典转换为哈希表?
  • 在最简单的层面上,我很懒惰。 Hashtable 类型的对象在很多地方都有使用。
  • 这本身并不是使用它的理由。字典和哈希表是在不同情况下使用的不同野兽。你知道, List 也被用在很多地方......那么为什么不使用它呢? :-s
  • @RoyDictus:字典只是一个通用的哈希表。它具有相同的目的。
  • @RoyDictus 如果我不想通过所有代码来使事情与字典一起工作,这是使用它的理由。

标签: c# .net


【解决方案1】:

最简单的方法是使用Hashtable的构造函数:

        var dictionary = new Dictionary<object, object>();
        //... fill the dictionary
        var hashtable = new Hashtable(dictionary);

【讨论】:

    【解决方案2】:
    Dictionary<int, string> dictionary = new Dictionary<int, string>
       {
          {1,"One"},
          {2,"Two"}
       };
    Hashtable hashtable = new Hashtable(dictionary);
    

    试试这个

    【讨论】:

      【解决方案3】:

      似乎很少想做,但最简单:

      var hash = new Hashtable();
      foreach(var pair in dictionary) {
          hash.Add(pair.Key,pair.Value);
      }
      

      (假设没有异常的“实现类型相等检查但未实现非类型相等检查”等)

      【讨论】:

      • 现在只需将其包含在 ToHashTable 扩展方法中,瞧!
      • 甚至还有一个constructor 做同样的事情。
      • 这就是我想做的事情。想知道是否有一种不那么明显的方法来做到这一点。不过,谢谢!
      【解决方案4】:

      您可能需要考虑使用带有IEqualityComparer 参数的Hashtable 构造函数重载:

      var hashtable = new Hashtable(dictionary, (IEqualityComparer) dictionary.Comparer); 
      

      这样,您的 Hashtable 使用与字典相同的 Comparer。例如,如果您的字典使用不区分大小写的字符串键,您可能希望 Hashtable 也区分大小写。例如:

      var d = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
      d.Add("a", "a");
      d.Add("b", "b");
      
      bool found;
      found = d.ContainsKey("A"); // true
      
      var hashtable1 = new Hashtable(d);
      var hashtable2 = new Hashtable(d, (IEqualityComparer) d.Comparer);
      
      found = hashtable1["A"] != null; // false - by default it's case-sensitive
      
      found = hashtable2["A"] != null; // true - uses same comparer as the original dictionary
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-15
        • 2015-12-13
        • 1970-01-01
        • 2021-02-06
        • 1970-01-01
        • 2011-09-21
        • 1970-01-01
        • 2011-08-01
        相关资源
        最近更新 更多