2011-10-19 19 views
8

將Dictionary 轉換爲Dictionary 我正在使用Dapper將2列結果集提取到字典中。 我注意到,智能感知顯示我.ToDictionary(),當我將鼠標懸停在結果集,但我不能讓它工作,因爲短小精悍使用動態性能/ expandoObject 如何使用Colllection.ToDictionary()

Dictionary<string, string > rowsFromTableDict = new Dictionary<string, string>(); 
using (var connection = new SqlConnection(ConnectionString)) 
{ 
    connection.Open(); 
    var results = connection.Query 
        ("SELECT col1 AS StudentID, col2 AS Studentname 
        FROM Student order by StudentID"); 
    if (results != null) 
    { 
    //how to eliminate below foreach using results.ToDictionary() 
    //Note that this is results<dynamic, dynamic> 
     foreach (var row in results) 
     { 
       rowsFromTableDict.Add(row.StudentID, row.StudentName); 
     } 
     return rowsFromTableDict; 
    } 
} 

謝謝

回答

14

嘗試:

results.ToDictionary(row => (string)row.StudentID, row => (string)row.StudentName); 

一旦你有一個動態對象,你對它做的每件事情以及相應的屬性和方法都是動態類型的。您需要定義一個明確的轉換,以將其重新轉換爲非動態類型。

+0

是的。那是做的。感謝 – Gullu

+0

+1,因爲它記住了'動態'。 –

+0

動態很好,但確實有很多陷阱需要轉換回靜態類型。 –

-1
if (results != null) 
{ 
    return results.ToDictionary(x => x.StudentID, x => x.StudentName);  
} 
+0

我知道這並不那麼簡單。錯誤無法將類型'System.Collections.Generic.Dictionary '隱式轉換爲'System.Collections.Generic.Dictionary <字符串,字符串>' – Gullu