CSharp - LINQ Cast

Introduction

Cast operator casts every element of an input sequence to an output sequence of the specified type.

Prototypes

public static IEnumerable<T> Cast<T>(
        this IEnumerable source);

Cast operator first argument, named source, is of type IEnumerable, not IEnumerable<T>.

Cast operator is designed to be called on classes that implement the IEnumerable interface, as opposed to the IEnumerable<T> interface.

You can call the Cast operator on a legacy collection as long as it implements IEnumerable, and an IEnumerable<T> output sequence will be created.

This operator will return an object that enumerates the source data collection, yielding each element cast to type T.

If the element cannot be cast to type T, an exception will be thrown.

This operator should be called only when it is known that every element in the sequence can be cast to type T.

Exceptions

ArgumentNullException is thrown if the source argument is null, and

InvalidCastException is thrown if an element in the input source collection cannot be cast to type T.

Converting an ArrayList to an IEnumerable<T>

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program//from   w ww  .  ja v  a2 s. c o m
{
    static void Main(string[] args)
    {
        ArrayList Students = Student.GetStudentsArrayList();
        Console.WriteLine("The data type of Students is " + Students.GetType());

        var seq = Students.Cast<Student>();
        Console.WriteLine("The data type of seq is " + seq.GetType());

        var emps = seq.OrderBy(e => e.lastName);
        foreach (Student emp in emps)
            Console.WriteLine("{0} {1}", emp.firstName, emp.lastName);

    }
}
class Student
{
    public int id;
    public string firstName;
    public string lastName;

    public static ArrayList GetStudentsArrayList()
    {
        ArrayList al = new ArrayList();

        al.Add(new Student { id = 1, firstName = "Joe", lastName = "Ruby" });
        al.Add(new Student { id = 2, firstName = "Windows", lastName = "Python" });
        al.Add(new Student { id = 3, firstName = "Application", lastName = "HTML" });
        al.Add(new Student { id = 4, firstName = "David", lastName = "Visual" });
        al.Add(new Student { id = 101, firstName = "Kotlin", lastName = "Fortran" });
        return (al);
    }

    public static Student[] GetStudentsArray()
    {
        return ((Student[])GetStudentsArrayList().ToArray());
    }
}

Result

The code first calls the GetStudentsArrayList method to return an ArrayList of Student objects.

Then we display the data type of the Students variable.

Next we convert that ArrayList to an IEnumerable<T> sequence by calling the Cast operator.

Then we display the data type of the returned sequence.

Lastly, we enumerate through that returned sequence to show that the ordering did indeed work.

Related Topics