CSharp - Cast for PLINQ

Introduction

The Cast operator converts a ParallelQuery to a ParallelQuery<T>.

You need to specify the type.

If there are any elements in the input sequence that are not of type T, then an exception will be thrown.

Prototypes

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

The following code demonstrates the use of the Cast operator to use a legacy collection as the source for a PLINQ query.

We apply the AsParallel operator to an ArrayList and then call Cast<string>() to create a ParallelQuery<string> for use in the PLINQ query.

Demo

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

class Program/* w ww  . j  ava  2s . co m*/
{
    static void Main(string[] args)
    {
          ArrayList list = new ArrayList() {
            "Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
    
          IEnumerable<string> results = list
              .AsParallel()
              .Cast<string>()
              .Where(p => p.Contains('o'))
        .Select(p => p);
    
       foreach (string president in results) {
          Console.WriteLine("Match: {0}", president);
       }
   }
}

Result

Related Topics