CSharp - Convert ArrayList to ParallelQuery<T>

Introduction

The following code defined an ArrayList.

We call the AsParallel method to create an instance of ParallelQuery and then call Cast<string> to create a ParallelQuery<string>, which we can then use as the basis for our PLINQ query.

The code shows what you need to do if you want to use PLINQ with a legacy data collection.

It is not enough to just call AsParallel; you also have to call the Cast<T> operator as well in order to get something that PLINQ can work with.

Demo

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

class Program//from   ww w .j a  v  a  2s.c o 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 Topic