2011-02-02 13 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; 
関連する問題