LINQ: OfType<T> Query Operator

LINQ: OfType<T> Query Operator

  • Comments 5



LINQ comes with the OfType<T> query operator, through which we can filter the required object type from a heterogeneous array.


Suppose below is the scenario where we have array with various types but will only retrieve the string type. Here we go with ease of life,



using System;

using System.Collections.Generic;

using System.Text;

using System.Query;

using System.Xml.XLinq;

using System.Data.DLinq;


namespace LINQConsoleApplication1_Oct11


    class Program


        static void Main(string[] args)


            object[] numbers = {"Wriju", 28, 12/12/2006, 3.3f, 1, "Tupur", 8.0};

            var strs = numbers.OfType<string>();


            Console.WriteLine("The list of friends..");



            foreach(var s in strs)









Output will look like


The list of friends..







Leave a Comment
  • Please add 8 and 8 and type the answer here:
  • Post
  • Nice sample, simple and easy to understand.

  • Nice sample was searching for a similar thing. Thanks.

  • Brilliant, I use this, shame books only give exmaples that cast and oftype are for use with legacy collections.

  • Add null as one of the array element to make clear how OfType<T> works with nulls (now it filters them out)

  • Is there a LINQ operator for it?

    Do you know of a list of all the linq operators built-in C# (such as where, join, select etc.)?

Page 1 of 1 (5 items)