C# Pass Lambda Expression as Method Parameter

Adam Levitt picture Adam Levitt · Jan 12, 2013 · Viewed 166k times · Source

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

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?

Answer

Oded picture Oded · Jan 12, 2013

Use a Func<T1, T2, TResult> delegate as the parameter type and pass it in to your 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>();   
  }  
}

You would call it:

getJobs((job, student) => {         
        job.Student = student;
        job.StudentId = student.Id;
        return job;
        });

Or assign the lambda to a variable and pass it in.