1

I need to create an IList with the keys and another IList with the values, taken from an IDictionary. How do I do it? I had to avoid generics (List<> and Dictionary<>) because the types inside them are user defined types not known at compile time.

I have a method that processes a DataTable and return a dictionary. The type of the dictionary keys are defined at runtime:

DataTable myDataTable = ....
Type dictionaryKeysType=Type.GetType("myType");
IDictionary myDictionary = ProcessDataTable (myDataTable, dictionaryKeysType);
IList keys= (IList)myDictionary.Keys;
IList values= (IList)myDictionary.Values;

How do I do it? I had to avoid generics (List<> and Dictionary<>) because the types inside them are user defined types not known at compile time. So, althought the method returns a 'Dictionary<>', I cant declare:

Dictionary<dictionaryKeysType, int> myDictionary = ProcessDataTable (myDataTable, dictionaryKeysType)

so I must receive it as a 'IDictionary'. Using 'var' is not a solution, as as the problem would come later when trying to cast it to 'Dictionary'

My code compiles but raises an exception when converting to IList. For example, if "myType" is "uint", I get: (Can't convert an object of type 'KeyCollection[System.UInt32,System.Int32]' to type 'System.Collections.IList').

Please, help :(

Kaikus
  • 1,001
  • 4
  • 14
  • 26

1 Answers1

1

I would suggest;

IList keys = myDictionary.Keys.ToList();
IList values = myDictionary.Values.ToList();

Please make sure that you include:

using System.Linq;

at the top of your file.

This will give you access to the .ToList() extension method.

Baldrick
  • 11,712
  • 2
  • 31
  • 35
  • Sorry :( That was my first choice, but but ICollection IDictionary doesn't implement .ToList(). – Kaikus Oct 13 '13 at 20:11
  • It doesn't by itself, but the extension method in System.Linq provides a .ToList() method which will do what you want. See the edited post above. – Baldrick Oct 14 '13 at 05:32
  • I don't know why, but doesn't. I am using Linq. I have the method 'private Dictionary foo(){}' and I I receive data in a 'IDictionary myDict = foo()' (I must do it because I do not know T type at compile time and I use 'MakeGenericMethod' and 'Invoke'). 'myDict.Keys' doesint implement 'ToList()' :( – Kaikus Oct 20 '13 at 21:45