CSharp - Combine AsParallel operator with OfType<T> operator to filter objects of a given type.

Introduction

The following code creates an ArrayList that contains the first three codeNames' names and three other objects.

We use the second AsParallel prototype on the ArrayList and then filter for the strings in the sequence by calling OfType<string>.

Only the strings in the sequence are used in the query.

Demo

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

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

Related Topic