C # 传递 Lambda 表达式作为方法参数

我有一个 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 表达式传递到调用这段代码的方法中,这样我就可以重用它。Lambda 表达式是我的。查询方法。我假设我想要使用一个 Action 或者 Func,但是我不太确定它的语法是什么或者它是如何工作的。有人能给我举个例子吗?

205791 次浏览

使用 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;
});

或者将 lambda 赋给一个变量,并将 传递给。

Lambda 表达式的类型为 Action<parameters>(如果它们没有返回值)或 Func<parameters,return>(如果它们有返回值)。在您的示例中,您有两个输入参数,并且您需要返回一个值,因此您应该使用:

Func<FullTimeJob, Student, FullTimeJob>

您应该使用委托类型并将其指定为命令参数。您可以使用内置的委托类型之一 -ActionFunc

在您的示例中,看起来您的委托接受两个参数,并返回一个结果,因此您可以使用 Func:

List<IJob> GetJobs(Func<FullTimeJob, Student, FullTimeJob> projection)

You could then call your GetJobs method passing in a delegate instance. This could be a method which matches that signature, an anonymous delegate, or a lambda expression.

另外,对于方法名应该使用 PascalCase-GetJobs,而不是 getJobs

如果我理解你需要以下代码。(通过参数传递表达式 lambda) 方法

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));

You can do the same in their class, see this is example.

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");

希望这个有用