TryGetValue () in linq expression with anonymous types

I cannot use TryGetValue()from a dictionary in a linq expression with an 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 can I get the value using the key in the dictionary?

+3
source share
1 answer

Most likely, the problem is that he does not know how to translate the getValueByKey call into an expression for your repository - because he cannot. First materialize the request using ToList () so that it now executes LINQ for objects, and then makes the selection an 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); 
} 
+3
source

Source: https://habr.com/ru/post/1737536/


All Articles