MaPi MaPi - 1 year ago 66
C# Question

Using AsSequential in order to preserve order

I am looking at this code

var numbers = Enumerable.Range(0, 20);
var parallelResult = numbers.AsParallel().AsOrdered()
.Where(i => i % 2 == 0).AsSequential();

foreach (int i in parallelResult.Take(5))

is supposed to make the resulting array sorted. Actually it is sorted after its execution, but if I remove the call to
, it is still sorted (since
) is called.

What is the difference between the two?

Answer Source

AsSequential is just meant to stop any further parallel execution - hence the name. I'm not sure where you got the idea that it's "supposed to make the resulting array sorted". The documentation is pretty clear:

Converts a ParallelQuery into an IEnumerable to force sequential evaluation of the query.

As you say, AsOrdered ensures ordering (for that particular sequence).