How to initialize a large array in parallel to PLINQ?
I'm 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 that would leave me with an array of elements of width x height null (uninitialized).
Of course, this should be possible, since this operation can simply be paralyzed (?).
What is the correct syntax for initialization with PLINQ?
+3
source to share
1 answer
I have no doubt there is a way to initialize an array with LINQ in parallel, but I would suggest just using Parallel.For instead:
var foo = new Foo[width * height];
Parallel.For(0, foo.Length, i => foo[i] = new Foo());
Edit: since you need the correct PLINQ solution (also fixed as pointed out):
var foo = Enumerable.Range(0, width * height)
.AsParallel()
.Select(x => new Foo())
.ToArray();
+5
source to share