Home

OfType

OfType is a LINQ operator that filters elements of a sequence, returning only those that are of a specified type. It is defined for both enumerable sequences (Enumerable.OfType<TResult>) and queryable sequences (Queryable.OfType<TResult>).

Behavior and return value: For each element in the source sequence, OfType tests whether the element can

Difference from Cast: Cast<T> attempts to cast every element in the source sequence to T and will

Usage and examples: Commonly used to extract elements of a specific type from a heterogeneous collection. For

Query translation: When used with IQueryable sources, OfType<TResult> translates into a type-check operation that can be

Notes: OfType is useful for selecting elements of a given type without requiring an explicit cast on

be
cast
to
the
specified
type
TResult.
If
the
cast
succeeds,
the
element
is
yielded
as
TResult;
otherwise
the
element
is
skipped.
The
operation
uses
deferred
execution,
meaning
elements
are
evaluated
as
the
resulting
sequence
is
enumerated.
The
result
is
an
IEnumerable<TResult>
for
Enumerable.OfType
and
an
IQueryable<TResult>
for
Queryable.OfType.
throw
an
exception
if
any
element
cannot
be
cast.
OfType<T>,
by
contrast,
filters
out
elements
that
cannot
be
cast,
returning
only
those
that
match
the
type.
example,
object[]
items
=
{
1,
"two",
3.0,
"four"
};
var
strings
=
items.OfType<string>();
//
yields
"two"
and
"four"
executed
by
the
underlying
query
provider.
Most
LINQ
providers
support
it,
though
translation
details
may
vary.
the
entire
sequence.
It
is
a
standard,
widely
supported
part
of
the
LINQ
set
of
operators.