Functional programming with Linq – Enumerable.OfType

Of all the methods available on the Enumerable class, OfType<T> is arguably one of the most useful and yet under utilized method.

For example, you have a list of Cat and Dog objects, all inheriting from a common Animal class, but occasionally you want to perform operations on only the dogs or cats, and that’s where OfType can come in handy:

public class Animal
{
    public string Name { get; set; }
}
public class Dog : Animal {}
public class Cat : Animal {}
…

var animals = new Animal[] { new Cat { Name = "Jess" },
                             new Cat { Name = "Tad" },
                             new Dog { Name = "Bob" } };
// get the dogs from the array of animals, functional style
var dogs = animals.OfType<Dog>();

// get the cats from the array of animals, true imperative style
var cats = new List<Cat>();
foreach (var animal in animals)
{
    if (animal is Cat)
        cats.Add(animal as Cat);
}

Of course, you could equally have filtered the array like this:

// lambda expression syntax
var cats = animals.Where(a => a is Cat).Select(a => a as Cat);
// query expression syntax
var cats = from a in animals where a is Cat select a as Cat;

But using OfType is far cleaner and expressive of your intent.

 

Learn to build Production-Ready Serverless applications

Want to learn how to build Serverless applications and follow best practices? Subscribe to my newsletter and join over 5,000 AWS & Serverless enthusiasts who have signed up already.

1 thought on “Functional programming with Linq – Enumerable.OfType”

Leave a Comment

Your email address will not be published. Required fields are marked *