Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TryGetValue() in linq expression with anonymous types

Tags:

c#

linq

.net-3.5

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?

like image 388
loviji Avatar asked Feb 13 '26 18:02

loviji


1 Answers

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); 
} 
like image 110
tvanfosson Avatar answered Feb 16 '26 07:02

tvanfosson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!