Introduction
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.
Syntax
- public static IEnumerable<TResult> OfType<TResult>(
- this IEnumerable source
- )
Example
Now let us see the simple example for better understanding. For that I have created one class and added different type values to it,
- public class Employee {
- public int ID {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- }
- ArrayList mixedList = new ArrayList();
- mixedList.Add(0);
- mixedList.Add("Gnanavel Sekar");
- mixedList.Add("Two");
- mixedList.Add(3);
- mixedList.Add(new Employee() {
- ID = 1, Name = "Gnanavel Sekar"
- });
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
- var stringResult = from s in mixedList.OfType<string>()
- select s;
- foreach (var item in stringResult)
- {
- Console.WriteLine(item);
- }
Now see the result, it returns the string type from the respective collection.
Okay now we shall try Integer type data
- var intResult = from s in mixedList.OfType<int>()
- select s;
- foreach (var item in intResult)
- {
- Console.WriteLine(item);
- }
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?
- var emp = from s in mixedList.OfType<Employee>()
- select s;
- foreach (var item in emp)
- {
- Console.WriteLine("ID : " + item.ID + ", Name : " + item.Name);
- }
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.