C# Pass Lambda Expression as Method Parameter

后端 未结 4 756
故里飘歌
故里飘歌 2020-11-29 00:21

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

public List getJobs(/* i want to pass the lambd         


        
4条回答
  •  天命终不由人
    2020-11-29 00:46

    Use a Func delegate as the parameter type and pass it in to your Query:

    public List getJobs(Func lambda)
    {
      using (SqlConnection connection = new SqlConnection(getConnectionString())) {
        connection.Open();
        return connection.Query(sql, 
            lambda,
            splitOn: "user_id",
            param: parameters).ToList();   
      }  
    }
    

    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.

提交回复
热议问题