【问题标题】:TryGetValue() in linq expression with anonymous types具有匿名类型的 linq 表达式中的 TryGetValue()
【发布时间】:2010-03-18 14:44:48
【问题描述】:

我不能在匿名类型的 linq 表达式中使用字典中的 TryGetValue()

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);
    }

请告诉我如何通过字典中的键获取值?

【问题讨论】:

  • 你得到什么错误信息?
  • @Luiscencio:在 Visual Studio 中,它没有红色下划线作为语法错误。但在调试中我发现了这样的事情:(“消息”:“表达式 LINQ to Entities 无法识别方法 \” System.String getValueByKey (System.String) \ “,因此它无法转换为存储库。", "StackTrace": "在 System.Data.Objects 中。
  • 刚刚问了一些与dis相关的问题:stackoverflow.com/questions/2466495/…
  • 所以..你需要实现一些讨厌的东西

标签: c# linq .net-3.5


【解决方案1】:

问题很可能是它不知道如何将对 getValueByKey 的调用转换为您的存储库的表达式——因为它不知道。首先使用 ToList() 实现查询,以便它现在执行 LINQ to Objects,然后对匿名类型执行选择。

[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); 
} 

【讨论】:

    猜你喜欢
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多