2011-11-06 7 views
2

매개 변수로 람다 식을 전달할 수있는 메서드를 만들고 싶습니다. 예를 들어,매개 변수로 람다

List<T> Select<T>(Predicate<T> criteria) 
{ 
    ... 
} 

표현식에서 발생한 필드와 값을이 방법으로 복구 할 수 있습니다.

사용의 예는 수 :

List<Contact> list = Select<Contact>(c => c.Id == 1); 

어떻게 필드와 값 식의 영어이

string field = something here that you retrieve in this case Id 
object value = something here make retrieve id here. 

죄송 같은

을받을 수 있나요, 제 모국어 스페인어입니다. 감사 인사와 인사.

+0

귀하의 질문에 대한 답변은 언어에 따라 다릅니다. 실제로 사용하는 언어를 알려주고 태그를 추가해야합니다. –

답변

2

매개 변수로 람다 식을 사용하려면 표현식을 SQL로 변환할지 여부에 따라 인수 유형을 Expression<Func<T,TResult>> 또는 Func<T,TResult>으로 설정해야합니다. 예를 들어,

public List<T> Select<T>(Expression<Func<T,bool>> selector) 
{ 
     return db.GetTable<T>().Where(selector); 
} 

주, 평가하거나 단순히 표현 형식이 요구되는 상황에서 사용하려는 경우 직접 표현을 검사 할 필요가 필요가없는 것이다.

3

일부 의견

public class LinqAsParameter 
{ 
    public class Dummy 
    { 
     public string Name { get; set; } 
     public int Age { get; set; } 
    } 

    public void Test() 
    { 
     var dummies = new List<Dummy> 
     { 
      new Dummy { Name = "Jon", Age = 30 }, 
      new Dummy { Name = "Will", Age = 27 }, 
     }; 

     // Calling the custom select method 
     IEnumerable<int> ages = dummies.CustomSelect(o => o.Age); 
    } 
} 

// extension class 
public static class IEnumerableExtenderLinqAsParameter 
{ 
    // extension method 
    public static IEnumerable<TResult> CustomSelect<TSource, TResult>(
     this IEnumerable<TSource> e 
     , Expression<Func<TSource, TResult>> exp) 
    { 
     // from the MemberExpression you can get the Member name 
     var memberExpression = exp.Body as MemberExpression; 
     var field = memberExpression.Member.Name; // name 
     var compiledExp = exp.Compile(); // compiling the exp to execute 
             // and retrieve the resulting value 

     // run the list an get the value for each item 
     foreach (TSource item in e) 
     { 
      yield return compiledExp(item); 
     } 
    } 
} 

유용한 존 소총의 게시물을 찾을 수있는 CustomSelect의 예 : MSDN에서 Reimplementing LINQ to Objects: Part 3 - "Select"

일부 참조 :