英語で読む

次の方法で共有


Enumerable.OfType<TResult>(IEnumerable) メソッド

定義

指定された型に基づいて IEnumerable の要素をフィルター処理します。

C#
public static System.Collections.Generic.IEnumerable<TResult> OfType<TResult> (this System.Collections.IEnumerable source);

型パラメーター

TResult

シーケンスの要素をフィルター処理する型。

パラメーター

source
IEnumerable

フィルター処理する要素を含む IEnumerable

戻り値

IEnumerable<TResult>

TResult 型の入力シーケンスの要素を格納する IEnumerable<T>

例外

sourcenullです。

を使用 OfType して の要素をフィルター処理する方法を次のコード例に IEnumerable示します。

C#
System.Collections.ArrayList fruits = new()
{
    "Mango",
    "Orange",
    null,
    "Apple",
    3.0,
    "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 as
// Where() can be applied to the ArrayList type after calling OfType().
IEnumerable<string> query2 =
    fruits.OfType<string>().Where(fruit =>
    fruit.Contains('n', StringComparison.CurrentCultureIgnoreCase));

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

注釈

このメソッドは、遅延実行を使用して実装されます。 即時戻り値は、アクションの実行に必要なすべての情報を格納する オブジェクトです。 このメソッドで表されるクエリは、オブジェクトがメソッドを直接呼び出GetEnumeratorすか、C# For Each または Visual Basic で を使用foreachして列挙されるまで実行されません。

メソッドはOfType<TResult>(IEnumerable)、 型と互換性のある TResultnull 以外の source 要素のみを返します。 要素を 型 TResultにキャストできない場合に例外を受け取る場合は、 を使用します Cast<TResult>(IEnumerable)

このメソッドは、 などのパラメーター化されていない型を持つコレクションに適用できる数少ない標準的なクエリ演算子メソッドの ArrayList1 つです。 これは、 型IEnumerableを拡張するためOfTypeです。 OfTypeは、パラメーター化された型に基づくコレクションだけでなく、パラメーター化IEnumerable<T>IEnumerableされていない型に基づくコレクションにも適用できます。

OfType 実装 IEnumerableするコレクションに を適用すると、標準のクエリ演算子を使用してコレクションに対してクエリを実行できます。 たとえば、 の型引数Objectを にOfType指定すると、C# または IEnumerable(Of Object) Visual Basic で型IEnumerable<Object>のオブジェクトが返され、標準のクエリ演算子を適用できます。

適用対象

製品 バージョン
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0