在lambda foreach中实例化一个类和调用方法

时间:2017-11-06 15:16:48

标签: c# lambda foreach

是否可以在ForEach lambda表达式中执行此操作?

reports.ForEach(x => new PublishReport(x)
      PublishReport.PublishReports());

我尝试做的是实例化PublishReport(带有类和方法名称的裸)类传递报表对象,然后调用PublishReport类的PublishReports方法。

我所做的工作是:

reports.ForEach(x => CallPublishReports(x));

private void CallPublishReport(Report report)
{
    PublishReport publishReport = new PublishReport(report);
    publishReport.PublishReports();
}

3 个答案:

答案 0 :(得分:2)

您正在寻找的代码如下所示:

reports.ForEach(x => (new PublishReport(x)).PublishReport());

或者

reports.ForEach(x => {
    var report = new PublishReport(x);
    report.PublishReports();
});

您也可以将ForEach替换为Select,因为前者仅存在于PLINQ afaik中。

答案 1 :(得分:2)

您可以首先使用Select创建实例,然后ForEach创建实例,如下所示:

reports
    .Select(r => new PublishReport(r))
    .ForEach(pr => pr.PublishReports());

答案 2 :(得分:1)

给lambda一个身体:

reports.ForEach(x => 
{
    PublishReport publishReport = new PublishReport(x);
    publishReport.PublishReports();
});