Skip to content
Eugene Sadovoi edited this page Jul 22, 2016 · 2 revisions

Filters the elements of an IEnumerable based on a specified type.

Syntax

OfType(type)

Parameters

type

The type to filter the elements of the sequence on.

Return Value

An Iterable that contains elements from the input sequence of type TResult.

Remarks

This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated.

The OfType method returns only those elements in source that can be cast to type TResult.

Example

The following code example demonstrates how to use OfType to filter the elements

var mix = [
    0, 
    new Number(1),
    "This is a simple string", 
    new String(), 
    new String("String created with constructor"), 
    new Date(), 
    true,
    Symbol.iterator,
    2,
    false,
    { Name: "asd"}, 
    [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ], 
    [ { id: 3, "name": "a" }, { id: 4, "name": "s" },
      { id: 5, "name": "d" }, { id: 6, "name": "f" } ], 
    new Boolean(true),
    {},
    new Boolean(false),
    3,
    function(){} 
];

// Create iterable
var iterable = Enumerable.asEnumerable(mix);

// Iterate over each type and select Numbers.
for (var value of iterable.OfType(Number)) {
    console.log(value);
}

/*  This code produces the following output:
    0
    1
    2
    3
*/

// Try the same for strings
for (var value of iterable.OfType(String)) {
    console.log(value);
}

/*  This code produces the following output:
    "This is a simple string"
    ""
    "String created with constructor"
*/

Try it out

Clone this wiki locally