如何在C#中将Dictionary<>转换为Hashtable?

12

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


1
你为什么需要那个?Hashtable非常特定,因为在键上计算的值会产生值的位置...而字典只是一个简单的(键,值)集合。你为什么想要将字典转换为Hashtable? - Roy Dictus
在最简单的层面上,我很懒。类型为Hashtable的对象在很多地方都被使用。 - jpints14
这本身并不是使用它的理由。字典和哈希表是在不同情况下使用的不同工具。你知道,List<int> 也被广泛应用于许多场合...那么为什么不使用它呢?:-s - Roy Dictus
2
@RoyDictus:字典只是一个通用的哈希表,它具有相同的作用。 - Meta-Knight
2
@RoyDictus 如果我不想通过编写所有代码来使事情与字典配合工作,那么使用它是有道理的。 - jpints14
啊,现在我明白了,抱歉。我不知道你是个业余爱好者。再次抱歉。 - Roy Dictus
4个回答

31

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

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

8
Dictionary<int, string> dictionary = new Dictionary<int, string>
   {
      {1,"One"},
      {2,"Two"}
   };
Hashtable hashtable = new Hashtable(dictionary);

试试这个


5

似乎很少有人想要这样做,但最简单的方法是:

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

(假设没有不寻常的“实现类型相等检查但不执行未类型化相等检查”等情况)

1
现在只需将此内容包含在“ToHashTable”扩展方法中,就完成了! - Dismissile
1
甚至有一个构造函数可以做同样的事情。 - Joey
这就是我想要做的。不知道是否有一种不那么明显的方法来实现它。不过,谢谢! - jpints14

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接