开发者

converting linq result to dictionary<string, int>

开发者 https://www.devze.com 2023-02-08 08:57 出处:网络
I\'m quite new to csharp and linq, so am having some trouble with a simple enough casting issue. I have a simple object-

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;
0

精彩评论

暂无评论...
验证码 换一张
取 消