3

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?

loviji
  • 12,620
  • 17
  • 63
  • 94
  • 2
    what error message do you get? – Luiscencio Mar 18 '10 at 14:47
  • @Luiscencio:in visual studio it's not red underlined as syntax error. but in debugging i catch something like this: ( "Message": "The expression LINQ to Entities does not recognize the method \" System.String getValueByKey (System.String) \ ", so it can not be converted into an expression of the repository.", "StackTrace": "in System.Data.Objects. – loviji Mar 18 '10 at 14:53
  • 1
    just asked something related to dis: http://stackoverflow.com/questions/2466495/why-do-linq-to-entities-does-not-recognize-certain-methods – Luiscencio Mar 18 '10 at 14:53
  • so.. you need to implement something nasty – Luiscencio Mar 18 '10 at 15:01

1 Answers1

3

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); 
} 
tvanfosson
  • 524,688
  • 99
  • 697
  • 795