Filtering Operator - OfType
The OfType operator filters the collection based on the ability to cast an element in a collection to a specified type.
OfType in Query Syntax
Use OfType operator to filter the above collection based on each element's type
IList mixedList = new ArrayList();
mixedList.Add(0);
mixedList.Add("One");
mixedList.Add("Two");
mixedList.Add(3);
mixedList.Add(new Student() { StudentID = 1, StudentName = "Bill" });
var stringResult = from s in mixedList.OfType<string>()
select s;
var intResult = from s in mixedList.OfType<int>()
select s;
Example: OfType operator in VB.Net:
Dim stringResult = From s In mixedList.OfType(Of String)()
The above sample queries will return items whose type is string in the mixedList. stringResult contains following elements after execution:
OneTwo
0
3
Bill
OfType in Method Syntax
You can use OfType<TResult>() extension method in linq method syntax as shown below.
var stringResult = mixedList.OfType<string>();
var intResult = mixedList.OfType<int>();
The stringResult
would contain following elements.
Two
Visit MSDN for more information on Filtering operators.