Functional programming with Linq – Enumerable.OfType

Yan Cui

I help clients go faster for less using serverless technologies.

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.


 

Whenever you’re ready, here are 4 ways I can help you:

  1. If you want a one-stop shop to help you quickly level up your serverless skills, you should check out my Production-Ready Serverless workshop. Over 20 AWS Heroes & Community Builders have passed through this workshop, plus 1000+ students from the likes of AWS, LEGO, Booking, HBO and Siemens.
  2. If you want to learn how to test serverless applications without all the pain and hassle, you should check out my latest course, Testing Serverless Architectures.
  3. If you’re a manager or founder and want to help your team move faster and build better software, then check out my consulting services.
  4. If you just want to hang out, talk serverless, or ask for help, then you should join my FREE Community.

 


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

Leave a Comment

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