C#通行证LAMBDA前pression的方法参数 [英] C# Pass Lambda Expression as Method Parameter

查看:124
本文介绍了C#通行证LAMBDA前pression的方法参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个lambda前pression,我希望能够通过周围和重用。这里的code:

I have a lambda expression that I'd like to be able to pass around and reuse. Here's the code:

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

这里的关键,是我希望能够通过我使用这里成的调用这个code中的方法拉姆达前pression,这样我就可以重新使用它。拉姆达前pression是我.Query方法中的第二个参数。我假设我想使用一个动作或函数功能,但我不能肯定的语法是这个或它如何工作相当。是否有人可以给我一个例子?

The key here, is I want to be able to pass the lambda expression that I'm using here into the method that's calling this code, so I can reuse it. The lambda expression is the second argument inside my .Query method. I'm assuming I'd want to use an Action or Func, but I'm not quite sure what the syntax is for this or how it quite works. Can someone please give me an example?

推荐答案

使用一个 函数功能:LT; T1,T2,TResult&GT; 委托作为参数类型,并把它传递到您的查询

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

或者拉姆达分配给一个变​​量,并通过的

这篇关于C#通行证LAMBDA前pression的方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆