简体   繁体   中英

Instantiating a class and calling method in lambda foreach

Is it possible to do this in a ForEach lambda expression?

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

What I'm trying to do is instantiate the PublishReport (bare with the class and method name) class passing a report object and then calling the PublishReports method of the PublishReport class.

The work around I have done is:

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

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

The code you're looking for looks something like this:

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

Or

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

You can replace ForEach , with Select , as well, as the former only exists in PLINQ afaik.

You can do it by first using Select to create the instances then ForEach over them like this:

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

Just give the lambda a body:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM