Ricardo Polo Jaramillo
Ricardo Polo Jaramillo

Reputation: 12338

Lambda and Foreach

I have this method:

public Wrapper(Action<string> codeBlock)
{
   //Code code code

        Parallel.ForEach<Computer>(Computers, computer =>
        {
                //CODE CODE 
               codeblock();

               //More code

        );
    //more code

 }

I use it to put a code block inside a wrapper that make important things to my app.

I invoke it using something like

Wrapper((s) => {

//My Code block
//code
//More code

});

I want to use the object computer of the collection Computers, created in the foreach of the wrapper, in my code block. So if I made something like this:

Wrapper((s) => {

//My Code block
 AFunction(computer);
//More code

});

It obviouslly fails because "computer" does not exists in the contexts where I invoke the wrapper, only exists inside the foreach of the wrapper.

So how could I accomplish this? Maybe I have an error design?

Upvotes: 2

Views: 182

Answers (1)

horgh
horgh

Reputation: 18563

Use

public Wrapper(Action<Computer> codeBlock)
{
    //...
    Parallel.ForEach<Computer>(Computers, computer =>
    {
           //...
           codeblock(computer);
           //...
    );
}

instead.

Wrapper((s) => {    // s is of type Computer here now
    //...
    AFunction(s);
    //...
});

Of course , you may use Action<T1,T2> (i.e. relevant delegate with the necessary number of parameters) if you need both Computer and string within your code block. Lambda expression would be changed accordingly: (s, comp) => { /*...*/ }

Upvotes: 8

Related Questions