Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize large array parallel with PLINQ?

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?

like image 526
Stefan Avatar asked May 05 '26 05:05

Stefan


1 Answers

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();
like image 152
willaien Avatar answered May 08 '26 03:05

willaien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!