C # 메서드 매개 변수로 Lambda 식 전달
전달하고 재사용 할 수있는 람다식이 있습니다. 코드는 다음과 같습니다.
public List<IJob> getJobs(/* i want to pass the lambda expr in here */) {
using (SqlConnection connection = new SqlConnection(getConnectionString())) {
connection.Open();
return connection.Query<FullTimeJob, Student, FullTimeJob>(sql,
(job, student) => {
job.Student = student;
job.StudentId = student.Id;
return job;
},
splitOn: "user_id",
param: parameters).ToList<IJob>();
}
여기서 핵심은 여기에서 사용하는 람다 식을이 코드를 호출하는 메서드에 전달하여 다시 사용할 수 있기를 원한다는 것입니다. 람다 식은 .Query 메서드 내의 두 번째 인수입니다. 나는 Action 또는 Func를 사용하고 싶다고 가정하고 있지만 구문이 무엇인지 또는 어떻게 작동하는지 잘 모르겠습니다. 누군가 나에게 예를 들어 줄 수 있습니까?
Func<T1, T2, TResult>
매개 변수 유형 으로 대리자를 사용하고 이를에 전달하십시오 Query
.
public List<IJob> getJobs(Func<FullTimeJob, Student, FullTimeJob> lambda)
{
using (SqlConnection connection = new SqlConnection(getConnectionString())) {
connection.Open();
return connection.Query<FullTimeJob, Student, FullTimeJob>(sql,
lambda,
splitOn: "user_id",
param: parameters).ToList<IJob>();
}
}
당신은 그것을 부를 것입니다 :
getJobs((job, student) => {
job.Student = student;
job.StudentId = student.Id;
return job;
});
또는 람다를 변수에 할당하고 전달 합니다 .
내가 이해하면 다음 코드가 필요합니다. (매개 변수로 표현식 람다 전달) 방법
public static void Method(Expression<Func<int, bool>> predicate) {
int[] number={1,2,3,4,5,6,7,8,9,10};
var newList = from x in number
.Where(predicate.Compile()) //here compile your clausuly
select x;
newList.ToList();//return a new list
}
호출 방법
Method(v => v.Equals(1));
당신은 그들의 수업에서 똑같이 할 수 있습니다. 이것은 예입니다.
public string Name {get;set;}
public static List<Class> GetList(Expression<Func<Class, bool>> predicate)
{
List<Class> c = new List<Class>();
c.Add(new Class("name1"));
c.Add(new Class("name2"));
var f = from g in c.
Where (predicate.Compile())
select g;
f.ToList();
return f;
}
호출 방법
Class.GetList(c=>c.Name=="yourname");
도움이 되었기를 바랍니다.
Lambda 식에는 Action<parameters>
(값을 반환하지 않는 경우) 또는 Func<parameters,return>
(반환 값이있는 경우) 유형이 있습니다. 귀하의 경우에는 두 개의 입력 매개 변수가 있고 값을 반환해야하므로 다음을 사용해야합니다.
Func<FullTimeJob, Student, FullTimeJob>
대리자 유형을 사용하고이를 명령 매개 변수로 지정해야합니다. - 당신은 대리인 유형에 내장 된 중 하나를 사용할 수 Action
및 Func
.
귀하의 경우에는 대리자가 두 개의 매개 변수를 사용하고 결과를 반환하므로 다음을 사용할 수 있습니다 Func
.
List<IJob> GetJobs(Func<FullTimeJob, Student, FullTimeJob> projection)
그런 다음 GetJobs
델리게이트 인스턴스를 전달하는 메서드 를 호출 할 수 있습니다. 이는 해당 서명, 익명 대리자 또는 람다 식과 일치하는 메서드 일 수 있습니다.
P.S. You should use PascalCase for method names - GetJobs
, not getJobs
.
참고URL : https://stackoverflow.com/questions/14297633/c-sharp-pass-lambda-expression-as-method-parameter
'Programming' 카테고리의 다른 글
sklearn 오류 ValueError : 입력에 NaN, 무한대 또는 dtype ( 'float64')에 비해 너무 큰 값이 있습니다. (0) | 2020.08.28 |
---|---|
Go의 쌍 / 튜플 데이터 유형 (0) | 2020.08.28 |
블록 기반 API 메서드에서 null이 아닌 nullable Objective-C 키워드를 사용하는 방법 (0) | 2020.08.28 |
Windows의 Emacs (0) | 2020.08.28 |
svn과 호환되는 Git 형식 패치? (0) | 2020.08.28 |