CSharp - Parallel LINQ AsParallel

Introduction

AsParallel operator converts data sequence into a ParallelQuery.

You are likely to use the AsParallel method every time you use PLINQ.

Prototypes

The AsParallel method has two prototypes that we will cover.

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

This prototype operates on an IEnumerable<T> and returns a ParallelQuery<T>, which can be used as the basis for a PLINQ query.

The Second AsParallel Prototype

public static ParallelQuery AsParallel(
          this IEnumerable source
)

The second prototype creates a ParallelQuery from an IEnumerable and exists to support legacy collections, such as System.Collections.ArrayList.

The ParallelQuery is not strongly typed and cannot be used as the basis for a PLINQ query without being converted to a ParallelQuery<T>.

You can cast a ParallelQuery to a ParallelQuery<T> by using the Cast<T> operator or filter the sequence to get the items that are instances of T by using the OfType<T> operator.

Demo

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

class Program//  ww  w. j av  a2s  . c  om
{
    static void Main(string[] args)
    {
          string[] codeNames = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
    
          ParallelQuery<string> pq = codeNames.AsParallel();
    
          IEnumerable<string> results = from p in pq
                    where p.Contains('o')
                    select p;
    
          foreach (string president in results) {
              Console.WriteLine("Match: {0}", president);
          }
    }
}

Result

Related Topics