CSharp - Converting a Legacy Collection to an IEnumerable<T> Using OfType operator.

Description

Converting a Legacy Collection to an IEnumerable<T> Using OfType operator.

Demo

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program/*from   ww  w  .  j av a 2s . co m*/
{
    static void Main(string[] args)
    {
        //  We'll build a legacy collection.  
        ArrayList arrayList = new ArrayList();
        arrayList.Add("Python");
        arrayList.Add("Java");
        arrayList.Add("Javascript");

        IEnumerable<string> names = arrayList.OfType<string>().Where(n => n.Length < 7);
        foreach (string name in names)
            Console.WriteLine(name);

    }
}

Result

Cast operator will attempt to cast every element in the collection to the specified type to be put into the output sequence.

If there is a type in the collection that cannot be cast to the specified type, an exception will be thrown.

OfType operator will only attempt to put those elements that can be cast to the type specified into the output sequence.

Related Topic