2011-10-19 8 views
8

Dapper를 사용하여 사전에 2 열 결과 집합을 가져옵니다. 나는 결과 집합 위에 마우스를 올려하지만 말끔 동적 속성을 사용하기 때문에이 동작하지 않습니다 때 IntelliSense를 나에게 .ToDictionary()를 보여줍니다 것으로 나타났습니다 /expandoObjectCollief.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