Filters IEnumerable elements based on the specified type.
Namespace:System. Linq
Assembly:System. Core (in System. Core. dll)
This method is implemented by using delayed execution. The real-time return value is an object that stores all information required to perform operations. OnlyGetEnumeratorMethod or useForeach(Or in Visual BasicFor Each.
OfType <(Of <(TResult>) (IEnumerable)Method returns onlySourceWhich can be convertedTResultType element. If the element cannot be convertedTResultType, but do not want to receive exceptions, use Cast <(Of <(TResult>) (IEnumerable ).
This method is one of the few standard query operator methods. The standard query operator method can be applied to a set containing non-parameterized types (such as ArrayList. This is becauseOfType <(Of <(TResult>)Extended type IEnumerable.OfType <(Of <(TResult>)It cannot be applied to a set Of parameter-based IEnumerable <(Of <(T>)> or a set Of non-parametric IEnumerable types.
By addingOfType <(Of <(TResult>)Applies to the set that implements IEnumerable to obtain the ability to query sets using standard query operators. For example, specify the Object type parameterOfType <(Of <(TResult>)Returns an object of the Type C #IEnumerable <Object>OrIEnumerable (Of Object)The standard query operator can be applied to this object.
C # code:
Code
System. Collections. ArrayList fruits = new System. Collections. ArrayList (4 );
Fruits. Add ("Mango ");
Fruits. Add ("Orange ");
Fruits. Add ("Apple ");
Fruits. Add (3.0 );
Fruits. Add ("Banana ");
// Apply OfType () to the ArrayList.
IEnumerable <string> query1 = fruits. OfType <string> ();
Console. WriteLine ("Elements of type 'string' are :");
Foreach (string fruit in query1)
{
Console. WriteLine (fruit );
}
// The following query shows that the standard query operators such
// Where () can be applied to the ArrayList type after calling OfType ().
IEnumerable <string> query2 =
Fruits. OfType <string> (). Where (fruit => fruit. ToLower (). Contains ("n "));
Console. WriteLine ("\ nThe following strings contain 'N ':");
Foreach (string fruit in query2)
{
Console. WriteLine (fruit );
}
// This code produces the following output:
//
// Elements of type 'string' are:
// Mango
// Orange
// Apple
// Banana
//
// The following strings contain 'N ':
// Mango
// Orange
// Banana