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.