LINQ Cast Operator

By Peter Bromberg

This LINQ Cast operator samples show how it enumerates the source sequence and tries to yield each item, cast to type T. In the case of failure, an InvalidCastException error will be thrown.

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

Because of its signature, which accepts any IEnumerable sequence, this method can be used to convert old nongeneric types to newer IEnumerable<T> types. This conversion makes it possible to query these types with LINQ even if the types are unaware of LINQ.

var fruits = new System.Collections.ArrayList();
      fruits.Add("apple");
      fruits.Add("mango");

           IEnumerable<string> query =
                 fruits.Cast<string>().Select(fruit => fruit);

             foreach (string fruit in query)
            {
               Console.WriteLine(fruit);
             }

             // This code produces the following output:
            //
            // apple
            // mango


LINQ Cast Operator  (775 Views)