Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 304
MaPi Avatar asked Oct 09 '13 07:10

MaPi


1 Answers

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

like image 97
Jon Skeet Avatar answered Sep 28 '22 14:09

Jon Skeet