CSharp - OfType for PLINQ

Introduction

The OfType operator creates a ParallelQuery<T> from a ParallelQuery by selecting only those sequence elements that are of type T.

It can consume items from a legacy collection containing mixed types without worrying about the exceptions that can arise using the Cast operator.

Prototypes

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

The following code contains an example of using OfType operator.

If you want a ParallelQuery<string>, then you call OfType<string>().

In the following code, we create a legacy collection that contains a mix of types and then use the OfType operator to create a ParallelQuery<string> that contains the string types from the collection.

Demo

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

class Program/*from   w  ww .  j  a va  2 s  .c  om*/
{
    static void Main(string[] args)
    {
    
          ArrayList list = new ArrayList();
    
          list.Add("Python");
          list.Add(23);
          list.Add("Java");
          list.Add(DateTime.Now);
          list.Add("Javascript");
          list.Add(new string[] { "apple", "orange" });
    
          IEnumerable<string> results = list
              .AsParallel()
              .OfType<string>()
              .Select(p => p);
    
          foreach (string president in results) {
              Console.WriteLine("Match: {0}", president);
          }

    }
}

Result