2010-03-18 42 views
3

我不能使用linq表達式中的匿名類型的字典中的TryGetValue()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); 
    } 

請告訴我如何通過字典中的鍵獲得價值?

+2

你會得到什麼錯誤信息? – Luiscencio 2010-03-18 14:47:31

+0

@Luiscencio:在visual studio中,它不是紅色下劃線的語法錯誤。但在調試中我發現這樣的東西: (「Message」:「表達式LINQ to Entities不能識別方法\」System.String getValueByKey(System.String)\「,所以它不能轉換成表達式存儲庫。「,」StackTrace「:」在System.Data.Objects。 – loviji 2010-03-18 14:53:01

+1

剛剛問了一些與dis相關的問題: http://stackoverflow.com/questions/2466495/why-do-linq-to-entities-does-不認識的某些方法 – Luiscencio 2010-03-18 14:53:57

回答

3

問題很可能是因爲它不知道如何將調用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); 
}