2013-10-13 38 views
1

我需要使用鍵和另一個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')。

請幫助:(

+1

'dic.Keys.ToList();'與'd.Values.ToList();'應該爲您生成兩個並行列表。 –

+0

對不起:(這是我的第一選擇,但但ICollection IDictionary不實現.ToList()。 – Kaikus

回答

1

我會建議;

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

請確保您有:

using System.Linq; 

在你的文件的頂部

此。將爲您提供訪問.ToList()擴展方法。

+0

對不起:(這是我的第一選擇,但ICollection IDictionary不實現.ToList()。 – Kaikus

+0

它doesn' t本身,但在System.Linq中的擴展方法提供了一個.ToList()方法,它將做你想做的。看看上面編輯過的帖子。 – Baldrick

+0

我不知道爲什麼,但沒有,我正在使用Linq。我有方法'私人字典 foo(){}'和II接收'IDictionary myDict = foo ()'中的數據(我必須這樣做,因爲我不知道T編譯時的類型,我使用'MakeGenericMethod'和'Invoke')。'myDict.Keys'doesint實現'ToList()':( – Kaikus