我有我想能够绕过和重用一个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>();
}
这里的关键,是我希望能够通过我使用这里成的呼唤这种代码的方法lambda表达式,这样我就可以重新使用。 λ表达式是我.Query方法内的第二个参数。 我假设我想使用的动作或函数功能,但我不肯定的语法是什么这或它如何工作相当。 有人可以给我一个例子吗?
使用一个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
方法传入一个委托实例。 这可能是一个其中该签名,匿名委托,或λ表达式匹配的方法。
PS您应该使用PascalCase方法名称- GetJobs
,不getJobs
。