Search code examples
.netlinqlambdaanonymous-methods

converting Linq/Lambda expressions to anonymous methods


I usually get code samples that uses lambda expressions. I am stil using .net 2.0, and find it difficult to work with such code, for example

foreach(var item in items)
{
    var catCopy = item;
    foreach(var word in words)
    {
        var wordCopy = word;
        var waitCallback = new WaitCallback(state =>
        {
            DoSomething(wordCopy, catCopy);
        });

        ThreadPool.QueueUserWorkItem(waitCallback);
    }
}

how do i convert such expression to any of its alternative(i.e non lambda code or anonymous methods)?

thanks


Solution

  • A lambda expression in C# is really just a delegate. Given your using .Net 2.0 you can use anonymous methods to define a delegate on the fly, so replace line of code with:

    var waitCallback = new WaitCallback(
                            delegate(object state) { 
                                 DoSomething(workCopy, catCopy); 
                            });