How to Use OfType in LINQ - C#

This is a quick guide on how to use the OfType LINQ operator.

The OfType command allows us to filter down a collection based on a specified type.

Let's take a look at an example with a simple object collection:

class UsingLinq 
{
    public static void Main (string[] args) 
    {
        var people = new List<Person>() 
        { 
            new Person() { PersonId = 1, Name = "Belinda", Age = 70 },
            new Person() { PersonId = 2, Name = "Betty",  Age = 81 },
            new Person() { PersonId = 3, Name = "Will",  Age = 18 },
            new Person() { PersonId = 4, Name = "Andy", Age = 70 },
            new Person() { PersonId = 5, Name = "Rob", Age = 15 }
        };
	}
}

class Person
{
    public int PersonId { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

    public Person() {}

    public void Introduce() 
    {
        Console.WriteLine($"My name is {Name}, and I am {Age} years old.");
    }
}

Using the method syntax, let's use OfType to return only the items of type String.

To do so, we need to create an ArrayList, and add both the people list, and a new string:

var mixedList = new ArrayList();
mixedList.AddRange(people);
mixedList.Add("Dave");

We can use OfType to differentiate between the Person objects, and the String object in the ArrayList:

public static void Main (string[] args) 
{
	var people = new List<Person>() 
	{ 
		new Person() { PersonId = 1, Name = "Belinda", Age = 70 },
		new Person() { PersonId = 2, Name = "Betty",  Age = 81 },
		new Person() { PersonId = 3, Name = "Will",  Age = 18 },
		new Person() { PersonId = 4, Name = "Andy", Age = 70 },
		new Person() { PersonId = 5, Name = "Rob", Age = 15 }
	};

	var mixedList = new ArrayList();
	mixedList.AddRange(people);
	mixedList.Add("Dave");
 
	var personList = mixedList.OfType<Person>(); 	foreach(Person p in personList)	{		p.Introduce();	} 
	var stringList = mixedList.OfType<String>(); 	foreach(String s in stringList)	{		Console.WriteLine($"This is just a string: {s}");	}}

This will give us the following output:

My name is Belinda, and I am 70 years old.
My name is Betty, and I am 81 years old.
My name is Will, and I am 18 years old.
My name is Andy, and I am 70 years old.
My name is Rob, and I am 15 years old.
This is just a string: Dave