2011-02-02 2 views
1

저는 csharp와 linq에 새롭기 때문에 간단한 캐스팅 문제로 인해 약간의 문제가 있습니다. 캐스팅 할 수 없습니다 : -linq 결과를 사전으로 변환합니다. <string, int>

public class AskQuestionFormView 
{ 
    public string QuestionText { get; set; } 
    public Dictionary<string,int> Location { get; set; } 
} 

하고 있지만 다음과 같은 오류 받고 있어요

AskQuestionFormView aqfv = new AskQuestionFormView(); 
     var result = from c in db.Countries 
        .ToDictionary(c => c.LocationName.ToString(), 
            c=>c.ID) 
        select c; 
     aqfv.Location = (Dictionary<string,int>)result; 

LINQ 쿼리 -

System.InvalidCastException을

나는 간단한 개체가 형식의 개체 'WhereSelectEnumerableIterator`2 [System.Collections.Generic.KeyValuePair`2 [System.String, System.Int32], System.Collections.Gen eric.KeyValuePair`2 [System.String, System.Int32]] '를 ​​입력하여'System.Collections.Generic.Dictionary`2 [System.String, System.Int32] '를 입력하십시오. 내가 잘못 뭐하는 거지

?

미리 감사드립니다.

답변

4

select c을 사용할 때 KeyValuePair을 반환하는 쿼리가 사전에서 쿼리를 시도하고 있습니다. 당신은 테이블에서 Dictionary를 생성해야하므로 대신이 시도 :

var result = db.Countries.ToDictionary(c => c.LocationName, c => c.ID); 
aqfv.Location = result; 
+0

. 매우 감사합니다. – Finnnn

0

이처럼보십시오 :

절대적으로 완벽
var result = (from c in db.Countries 
       select c).ToDictionary(c => c.LocationName.ToString(), 
           c=>c.ID); 
    aqfv.Location = result; 
관련 문제