[LINQ Operators] Cast

The “Cast” operator is used to cast the elements of a sequence to a given type. It is mainly used to convert a sequence from “IEnumerable” to “IEnumerable<T>”.

 

1. Sample Data Object

To test examples, you need to include the <data classes> in your project.

 

2. “Cast” operator

  • Deferred operator
  • Purpose: Cast

 

3. Prototypes

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

The “Cast()” operator tries to cast every element in a sequence to an output sequence of the specified type. If you have a legacy collection and want to use LINQ, you need to convert the sequence from “IEnumerable” to “IEnumerable<T>“.

If any element cannot be casted to type <T>, the “Cast() operator will throw an exception. To obtain only those elements that can be cast to type <T>, use the “OfType<T>” operator.

 

4. Example 1 (Standard Operator)

var emps = Employee.GetEmployees();

var empList = new System.Collections.ArrayList();
foreach (object emp in emps)
{
  empList.Add(emp);
}

// var newEmps = empList.Where(...) // not possible
var newEmps = empList.Cast<Employee>().Where(e => e.CityID == 1);
foreach (var e in newEmps)
{
  Console.WriteLine($"{e.Name}");
}

 

5. Example 2 (Query Expression)

There’s no corresponding query expression for the “Cast()” operator.

 

6. Example 3 (Standard Operator) – Casting Error

object[] nums = {1, 2, 3.3, 4, 5.5};

var numberList = new System.Collections.ArrayList();
foreach (object num in nums)
{
  numberList.Add(num);
}

try
{
  // will thrown an InvalidCastException
  var intNumbers = numberList.Cast<Int32>();
  foreach (var num in intNumbers)
  {
    Console.WriteLine($"{num}");
  }
}
catch (InvalidCastException e)
{
  Console.WriteLine(e.Message);
}

The output will be “1 2 Specified cast is not valid”.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s