我需要使用鍵和另一個IList創建具有從IDictionary中取得的值的IList。我該怎麼做?我必須避免使用泛型(列表<>和字典<>),因爲它們中的類型是編譯時未知的用戶定義類型。C#將IDictionary轉換爲兩個ILists
我有一個方法處理DataTable並返回一個字典。字典鍵的類型在運行時定義:
DataTable myDataTable = ....
Type dictionaryKeysType=Type.GetType("myType");
IDictionary myDictionary = ProcessDataTable (myDataTable, dictionaryKeysType);
IList keys= (IList)myDictionary.Keys;
IList values= (IList)myDictionary.Values;
我該怎麼做?我必須避免使用泛型(列表<>和字典<>),因爲它們中的類型是編譯時未知的用戶定義類型。所以,althought方法返回一個「詞典<>」,我不能聲明:
Dictionary<dictionaryKeysType, int> myDictionary = ProcessDataTable (myDataTable, dictionaryKeysType)
,所以我必須接受它作爲一個「IDictionary的」。使用「var」不是解決方案,因爲稍後將其轉換爲「字典」時會出現問題。
我的代碼編譯時轉換爲IList時引發異常。例如,如果「myType」是「uint」,我得到:(不能將類型'KeyCollection [System.UInt32,System.Int32]'的對象轉換爲鍵入'System.Collections.IList')。
請幫助:(
'dic.Keys.ToList();'與'd.Values.ToList();'應該爲您生成兩個並行列表。 –
對不起:(這是我的第一選擇,但但ICollection IDictionary不實現.ToList()。 – Kaikus