Uses Of OfType In LINQ

The OfType is a filter operation and it filters the collection based on the ability to cast an element in a collection to a specified type. It searches elements by their type only.
  1. public static IEnumerable<TResult> OfType<TResult>(  
  2. this IEnumerable source  
  3. )  
Now let us see the simple example for better understanding. For that I have created one class and added different type values to it,
  1. public class Employee {  
  2.     public int ID {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public string Name {  
  7.         get;  
  8.         set;  
  9.     }  
  10. }  
  11. ArrayList mixedList = new ArrayList();  
  12. mixedList.Add(0);  
  13. mixedList.Add("Gnanavel Sekar");  
  14. mixedList.Add("Two");  
  15. mixedList.Add(3);  
  16. mixedList.Add(new Employee() {  
  17.     ID = 1, Name = "Gnanavel Sekar"  
  18. });  
I already told you that we can filter the desired type value using the OfType, shall we try now?
First I am going to try the string
  1. var stringResult = from s in mixedList.OfType<string>()  
  2. select s;  
  3. foreach (var item in stringResult)  
  4. {  
  5.    Console.WriteLine(item);  
  6. }  
Now see the result, it returns the string type from the respective collection.
Okay now we shall try Integer type data
  1. var intResult = from s in mixedList.OfType<int>()  
  2. select s;  
  3. foreach (var item in intResult)  
  4. {  
  5.    Console.WriteLine(item);  
  6. }  
Now see the result, it returns the integer type from the respective collection
Okay, we got the clear picture, it gives the desired type of data, shall we try the class as a type?
  1. var emp = from s in mixedList.OfType<Employee>()  
  2. select s;   
  3. foreach (var item in emp)  
  4. {  
  5.    Console.WriteLine("ID : " + item.ID + ", Name : " + item.Name);  
  6. }  
Now see the result, it returns the employee type from the respective collection
Benefits of OfType 
  • The OfType operator filters the collection based on a given type
  • Where and OfType extension methods can be called multiple times in a single LINQ query.
I hope you got a clear picture about OfType Operator in linq. Refer attached to sample for your reference.