CSharp - Creating a Parallel LINQ Query

Introduction

Using Parallel LINQ, known as PLINQ, is similar to using LINQ to Objects.

In a regular LINQ to Objects query, the data source is an IEnumerable<T>, where T is the data type.

The LINQ engine automatically switches to using PLINQ when the data source is an instance of the ParallelQuery<T> type.

We can convert any IEnumerable<T> into a ParallelQuery<T> by using the AsParallel method.

Demo

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

class Program/*  w w w.j  a  v a  2s.co m*/
{
    static void Main(string[] args)
    {
        string[] codeNames = { "Python", "Java", "Javascript", "Bash", "C++", "Oracle" };

        // sequential LINQ query
        IEnumerable<string> results = from p in codeNames
                                      where p.Contains('o')
                                      select p;

        foreach (string president in results)
        {
            Console.WriteLine("Sequential result: {0}", president);
        }
        // Parallel LINQ query
        results = from p in codeNames.AsParallel()
                  where p.Contains('o')
                  select p;

        foreach (string president in results)
        {
            Console.WriteLine("Parallel result: {0}", president);
        }
    }
}

Result

The first query uses regular LINQ to Objects to process each of the codeNames to find those names that contain the letter o.

We get the IEnumerable<string> as the result of the query and print out each matching name.

The second query does exactly the same thing, but we have used the AsParallel method.

AsParallel converts our data source into a ParallelQuery, which automatically engages Parallel LINQ.

The sequential results are in alphabetical order, but the parallel results are not.

Related Topic