Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashtable to Dictionary

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.

like image 261
NoBullMan Avatar asked Mar 17 '26 17:03

NoBullMan


2 Answers

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;
}
like image 117
Reed Copsey Avatar answered Mar 20 '26 06:03

Reed Copsey


Enumerable.Cast is in the System.Linq namespace. Unfortunately, LINQ is not part of .NET 2. You will have to upgrade to at least version 3.5.

like image 35
Martin Liversage Avatar answered Mar 20 '26 06:03

Martin Liversage



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!