By default, PLINQ does not preserve the order out of a source collection. Because PLINQ processes items in a data collection concurrently using multiple threads, the items are returned unordered. This is by design, because maintaining the original ordering of a sequence adds overhead, and in most cases, that overhead may not be necessary.
However, when you need to preserve order, PLINQ provides a simple way to accomplish it. In this recipe, we are going to create a Console
application that creates two collections of numbers, performs an ordered query on one collection, and the default unordered query on the other collection, and looks at the results.
Let's open up Visual Studio and see how to preserve order on parallel LINQ queries.
Start a new project using the C# Console Application project template, and assign
PreserveOrder
as the Solution name.Add the following
using
directives to the top of yourProgram
class:using System; using System.Collections...