Perform a computationally intensive operation on a large collection of items in LINQ

AsParallel() in C# is a method in the Parallel LINQ (PLINQ) library, which is a parallel implementation of LINQ (Language Integrated Query). PLINQ enables you to perform queries in parallel, utilizing multiple processors or cores to speed up query execution.

using System;
using System.Linq;


class Program
{
    static void Main()
    {
        // An array of numbers
        int[] numbers = Enumerable.Range(1, 1000000).ToArray();


        // Using AsParallel to enable parallel processing
        var evenNumbers = numbers.AsParallel()
                                 .Where(n => n % 2 == 0)
                                 .ToArray();


        Console.WriteLine($"Found {evenNumbers.Length} even numbers.");
    }
}


If order is important, you can use the AsOrdered() method after AsParallel() to maintain the original order of the elements in the output. However, this might reduce the performance benefits.

var evenNumbers = numbers.AsParallel()
                         .AsOrdered()
                         .Where(n => n % 2 == 0)
                         .ToArray();


You can control the degree of parallelism using the WithDegreeOfParallelism method.

var evenNumbers = numbers.AsParallel()
                         .WithDegreeOfParallelism(4) // Limits to 4 concurrent threads
                         .Where(n => n % 2 == 0)
                         .ToArray();


When to Use AsParallel()

  • You have a large dataset.
  • The operations are CPU-bound (intensive computations).
  • Order of execution is not critical.
  • You have multiple cores or processors available.