[LINQ Operators] OfType

The “OfType” operator filters the elements of a sequence based on a type. It is used to convert a sequence from a legacy collection “IEnumerable” to the LINQ collection “IEnumerable<T>”.

 

1. Sample Data Object

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

 

2. “OfType” operator

  • Deferred operator
  • Purpose: Cast / Filter

 

3. Prototypes

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

The “OfType()” operator creates an output sequence containing only elements that can be successfully cast to a specified type.

If an element cannot be cast to type <T>, this method will not throw an exception and just skip the element.

 

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.OfType<Employee>().Where(e => e.CityId == 2);
foreach (var e in newEmps)
{
  Console.WriteLine($"{e.Name}");
}

 

5. Example 2 (Query Expression)

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

 

6. Example 3 (Standard Operator) – Cast Error

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

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

var intNumbers = numberList.OfType<Int32>(); // no exception
foreach (var num in intNumbers)
{
  Console.WriteLine($"{num}"); // 1,2,4
}

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