Michael Weston Michael Weston - 3 months ago 12
C# Question

How would this Parallel.ForEach loop be done without using lambda expressions?

Trying to understand what using delegates in C# is like without lambda expressions. I understand their function, but still blurry on their syntax. What would this piece of code look like without using => lambda shortcut?

//pictureList is a string array of C:\Pictures\pic_1 through 10.jpeg file paths
Parallel.ForEach(pictureList, currentPic =>
{
string picName = Path.GetFileName(currentPic);
using (Bitmap bitmap = new Bitmap(currentPic))
{
bitmap.RotateFlip(RotateFlipType.Rotate180FlipNone);
bitmap.Save(Path.Combine(newDir, picName));
}
}
);

Answer

Lambda is not a "shortcut", it is a way to produce delegate objects "inline" (i.e. without defining a separate method).

You can use the old way of producing delegates inline (i.e. anonymous methods), like this

Parallel.ForEach(pictureList, delegate(Image currentPic) {
    ...
});

or define a separate method for it, like this:

Parallel.ForEach(pictureList, ProcessPicture);
...
static void ProcessPicture(Image currentPic) {
    ...
}