HASHTABLE TO DICTIONARY

Ankita Pandey

Total Post:183

Points:1285
Posted by  Ankita Pandey
C# 
C#
 1482  View(s)
Ratings:
Rate this:

I am trying to convert a hashtable to disctionary and found a a question here: 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);

}

When I try to use it, there is an error in table.Cast; intellisense does not show "Cast" as a valid method.
  1. Pravesh Singh

    Post:412

    Points:2888
    Re: Hashtable to Dictionary

    Hi Ankita,

    Enumerable.Cast doesn't exist in .NET 2, nor does most of the LINQ related methods (such as ToDictionary).

    You'll need to do this manually via looping:

    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;

    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!