【问题标题】:Hashtable to Dictionary哈希表到字典
【发布时间】:2014-01-04 07:25:34
【问题描述】:

我正在尝试将哈希表转换为字典,并在这里发现了一个问题: convert HashTable to Dictionary in C#

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

当我尝试使用它时,table.Cast 有错误; intellisense 不会将“Cast”显示为有效方法。

【问题讨论】:

  • C# 2 不支持 LINQ,所以你不能这样做。
  • 你有using System.Linq吗?
  • 谢谢塞巴斯蒂安;那是我的问题;我错过了“使用..”这一行。我现在拥有的代码行工作得很好。我也试过“字典 dict = HashtableToDictionary(htOffice);”我的哈希表使用字符串作为键,使用 int 作为值。不知道如何将您的回复标记为答案。

标签: c# .net dictionary hashtable c#-2.0


【解决方案1】:

Enumerable.Cast 位于 System.Linq 命名空间中。不幸的是,LINQ 不是 .NET 2 的一部分。您必须至少升级到 3.5 版。

【讨论】:

    【解决方案2】:

    Enumerable.Cast 不存在于 .NET 2 中,大多数 LINQ 相关方法(例如 ToDictionary)也不存在。

    您需要通过循环手动执行此操作:

    public static Dictionary<K,V> HashtableToDictionary<K,V> (Hashtable table)
    {
        Dictionary<K,V> dict = new Dictionary<K,V>();
        foreach(DictionaryEntry kvp in table)
            dict.Add((K)kvp.Key, (V)kvp.Value);
        return dict;
    }
    

    【讨论】:

    猜你喜欢
    • 2013-03-21
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    • 2013-01-15
    • 2011-06-10
    • 1970-01-01
    相关资源
    最近更新 更多