开发者

TryGetValue() in linq expression with anonymous types

I can't use TryGetValue() from dictionary in linq expression with anonymous type.

Dictionary<string, string> dict = new Dictionary<string, string>()
{
            {"1", "one"},
            {"2", "two"},
     开发者_开发百科       {"3", "three"}
};

public string getValueByKey(string value)
{
    string sColumnType = "";
    dict.TryGetValue(value, out sColumnType);
    return sColumnType;
}

[WebMethod]
    public string getData(string name)
    {
       var result = (from z in myObject
                      where z.name == name
                      select new
                      {
                          a = z.A,
                          b = z.B,
                          c=getValueByKey(z.C)  //fails there

                      }).ToList();



        return new JavaScriptSerializer().Serialize(result);
    }

Please, tell me how I can get value by key in dictionary?


The problem is most likely that it doesn't know how to translate the call to getValueByKey into an expression for your repository -- because it can't. Materialize the query first, using ToList(), so that it's now doing LINQ to Objects, then do the selection to the anonymous type.

[WebMethod] 
public string getData(string name) 
{ 
   var result = myObject.Where( z => z.name == name )
                        .ToList()
                        .Select( k => 
                            new 
                            { 
                                a = k.A, 
                                b = k.B, 
                                c = getValueByKey(k.C)
                            })
                        .ToList(); 

    return new JavaScriptSerializer().Serialize(result); 
} 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜