CSharp - Parallel LINQ AsSequential

Introduction

The AsSequential operator is the opposite of the AsParallel operator.

It forces sequential execution by converting a ParallelQuery<T> to an IEnumerable<T>.

Prototypes

public static IEnumerable<T> AsSequential<T>(
    this ParallelQuery<T> source
)

The AsSequential operator enables and disables parallel execution in different parts of a multipart query.

Demo

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

class Program//w  w w.  j av a2 s.  c  o  m
{
    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)
              .AsSequential()
              .Where(p => p.Contains('e'))
              .Select(p => p);
    
          foreach (string president in results) {
              Console.WriteLine("Match: {0}", president);
          }
    }
}