2

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.

Community
  • 1
  • 1
NoBullMan
  • 2,032
  • 5
  • 40
  • 93
  • 2
    C# 2 does not support LINQ, so you can't do that. – SLaks Dec 16 '13 at 19:08
  • 1
    do you have `using System.Linq`? – Sebastian Dec 16 '13 at 19:16
  • Thank you Sebastian; that was my issue; I was missing the "using .." line. The line of code that I have now works just fine. I also tried "Dictionary dict = HashtableToDictionary(htOffice);" where my hash table was using a string as key and an int as value. Not sure how to mark your response as the answer. – NoBullMan Dec 16 '13 at 21:02

2 Answers2

8

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;
}
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 2
    One cool note is you **can** use extension methods in 2.0 if you are using a compiler that supports it (VS 2008 and above). [You just need to declare the attribute flag the compiler transparently adds when you create a extension method.](http://stackoverflow.com/questions/11346554/can-i-use-extension-methods-and-linq-in-net-2-0-or-3-0) – Scott Chamberlain Dec 16 '13 at 19:18
2

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.

Martin Liversage
  • 104,481
  • 22
  • 209
  • 256