I'm quite new to csharp and linq, so am having some trouble with a simple enough casting issue.
I have a simple object -
public class AskQuestionFormView
{
public string QuestionText { get; set; }
public Dictionary<string,int> Location { get; set; }
}
and a linq query
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;
but I'm getting the following error -
System.InvalidCastException: Unable to cast object of开发者_Python百科 type 'WhereSelectEnumerableIterator`2[System.Collections.Generic.KeyValuePair`2[System.String,System.Int32],System.Collections.Generic.KeyValuePair`2[System.String,System.Int32]]' to type 'System.Collections.Generic.Dictionary`2[System.String,System.Int32]'.
What am I doing wrong?
Thanks in advance.
Your query is attempting to query from the dictionary, which is returning a KeyValuePair
when you use select c
. You just need to generate a Dictionary
from the table, so try this instead:
var result = db.Countries.ToDictionary(c => c.LocationName, c => c.ID);
aqfv.Location = result;
Try it like this:
var result = (from c in db.Countries
select c).ToDictionary(c => c.LocationName.ToString(),
c=>c.ID);
aqfv.Location = result;
精彩评论