CSharp - Parallel LINQ AsUnordered

Introduction

AsUnordered operator undoes the effect of applying the AsOrdered operator.

This can be useful in multipart queries where you need ordering in only one part.

Prototypes

public static ParallelQuery<T AsUnordered<T>(
          this ParallelQuery<T> source
)

The following code demonstrates the use of the AsUnordered operator in a two-stage PLINQ query.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

class Program/*from  ww  w.  ja  v a  2 s. c om*/
{
    static void Main(string[] args)
    {
              string[] codeNames = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
        
        IEnumerable<string> results = codeNames
            .AsParallel()
            .AsOrdered()
            .Where(p => p.Contains('o'))
            .Take(5)
            .AsUnordered()
            .Where(p => p.Contains('e'))
            .Select(p => p);
        
        foreach (string president in results) {
            Console.WriteLine("Match: {0}", president);
        }
    }
}

In this code we first find all the codeNames' names that contain the letter o preserving the order of the results using the AsOrdered operator.

We call AsUnordered to avoid PLINQ incurring the overhead of sorting the results.