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 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
KeyValuePairwhen you useselect c. You just need to generate aDictionaryfrom the table, so try this instead: