In C#, the OfType
method is used to filter a collection and retrieve only the elements that are of a specific type or that can be cast to a particular type. It is part of LINQ (Language-Integrated Query) and can be used with collections that implement the IEnumerable
interface.
The syntax for using OfType
is as follows:
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<object> mixedList = new List<object> { 1, "Hello", 2, "World", 3.14, true }; IEnumerable<string> stringsOnly = mixedList.OfType<string>(); foreach (string str in stringsOnly) { Console.WriteLine(str); } } }
In this example, we have a mixed list of objects that include integers, strings, doubles, and a boolean value. We want to retrieve only the elements of type string
from this collection.
- First, include the necessary using directives (
using System;
,using System.Collections.Generic;
, andusing System.Linq;
). - Create a list (
mixedList
) with a combination of different types. - Use the
OfType<string>()
method on themixedList
to filter out only the elements that are of typestring
. - Loop through the filtered collection (
stringsOnly
) using aforeach
loop and print the strings to the console.
Output of the code will be:
Hello World