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

本文关键字:方法 参数 表达式 传递 Lambda | 更新日期: 2023-09-27 17:52:13

我有一个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表达式是. query方法中的第二个参数。我假设我想使用Action或Func,但我不太确定语法是什么,或者它是如何工作的。有人能给我举个例子吗?

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

使用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赋值给一个变量并将传递给 in。

如果我理解你需要以下代码。(通过参数传递表达式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));

你可以在他们的类中做同样的事情,看看这个例子。

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>

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

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

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

你可以调用你的GetJobs方法传递一个委托实例。可以是匹配签名的方法、匿名委托或lambda表达式。

注:您应该使用PascalCase作为方法名——GetJobs,而不是getJobs