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.

  • http://furminatordogbrush.com Chanel Dezzutti

    Your post is very interesting. Very informative and just what I was searching for. I will see if I can find some additional useful ideas. Thank you.