How to initialize large array parallel with PLINQ?

403 views Asked by At

I am trying to initialize a simple (but large) array, using PLINQ:

void Test(int width, int height)
{
    var foo = new Foo[width * height];
    foo.AsParallel().ForAll(c => new Foo());
}

But this will leave me with an array of width x height null (uninitialized) elements.

Surely this must be possible since this operation can simply be paralyzed(?).

What is the correct syntax to perform the initialization with PLINQ?

1

There are 1 answers

5
willaien On BEST ANSWER

I don't doubt that there is a way to initialize an array with LINQ in parallel, but, I'd suggest simply using Parallel.For instead:

var foo = new Foo[width * height];
Parallel.For(0, foo.Length, i => foo[i] = new Foo());

Edit: Since you want a proper PLINQ solution (also, fixed typo as you pointed out):

var foo = Enumerable.Range(0, width * height)
                    .AsParallel()
                    .Select(x => new Foo())
                    .ToArray();