LINQ OfType Filtering Operator

C#  LINQ  C#  linq 

OfType comes in Filtering operator category. Here is list of all Query Operators.

LINQ OfType operator filter the objects from a collection based on Types. In a collection, we have multiple elements of different Types and we have to select only those objects from the collection that are of specific Type.

C# Example of OfType Operator in Query Syntax

abstract class Course
{
    public int ID { get; set; }
    public string Subject { get; set; }
    public int Rank { get; set; }
}

internal class FreeCourse : Course
{

}

internal class PaidCourse : Course
{
    public decimal Fees { get; set; }
}

List<Course> courses = new List<Course>();
courses.Add(new FreeCourse
{
    ID = 1,
    Subject = "LINQ Tutorials",
    Rank = 5
});

courses.Add(new FreeCourse
{
    ID = 2,
    Subject = ".NET Threading Tutorials",
    Rank = 4
});

courses.Add(new PaidCourse
{
    ID = 3,
    Subject = "Learn WPF",
    Rank = 3
});

courses.Add(new PaidCourse
    {
        ID = 4,
        Subject = "Datagrid Tutorials",
        Rank = 3
    });

var paidCourses = from course in courses.OfType<PaidCourse>()
                    select course;

var freeCourses = from course in courses.OfType<FreeCourse>()
                    select course;

Try It

Paid Courses
    Learn WPF
    Datagrid Tutorials
Free Courses
    LINQ Tutorials
    .NET Threading Tutorials

In the above C# example, we have one abstract class Course and two inherit classes FreeCourse and PaidCourse. We add all courses in List<Course> sequence. In the last, we select only paid courses from the collection by using OfType operator and passing PaidCourse Type as generic argument and select only free courses from the collection using OfType and passing FreeCourse as generic argument.

C# Example of OfType Operator in Method Syntax

var paidCourses = courses.OfType<PaidCourse>();

var freeCourses = courses.OfType<FreeCourse>();

Try It

Method syntax is more easy than Query syntax. We called a OfType method on sequence class.

Difference between Where and OfType operator

  1. OfType filter elements based on their Types.
  2. Where Operator filter elements based on the given predicate function.

Difference between OfType and Cast operator

  1. Cast operator try to cast all elements to a given Type. If all elements are not of a given Type then it throws an exception.
  2. OfType select only those elements which are of given Type.

Join our newsletter and get an occasional email with a technology and DotNetPattern.com news update.