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))
    Console.WriteLine(i);

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

What is the difference between the two?

Jon Skeet
people
quotationmark

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).

people

See more on this question at Stackoverflow