2010-03-18 2 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

+0

@Luiscencio : Visual Studio에서 구문 오류로 빨간색 밑줄이 그어지지 않았습니다. 하지만 디버깅을 나는 이런 식으로 잡는다 : ("메시지": "LINQ to Entities식이 \"System.String getValueByKey (System.String) \ "메서드를 인식하지 못하므로 식으로 변환 할 수 없습니다. 리포지토리. ","StackTrace ":"System.Data.Objects. – loviji

+1

은 dis와 관련된 무언가를 물었습니다 : http://stackoverflow.com/questions/2466495/why-do-linq-to-entities-does- 고맙습니다 - 특정 - 방법을 – Luiscencio

답변

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); 
} 
관련 문제