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>

IEnumerable<T>,其中包含輸入序列中型別為 TResult 的項目。

例外狀況

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# 或 foreachFor Each Visual Basic 中使用 來列舉對象,否則不會執行這個方法所代表的查詢。

方法OfType<TResult>(IEnumerable)只會傳回中非 Null 且與 類型TResult相容的專案source。 若要在項目無法轉換成類型 TResult時接收例外狀況,請使用 Cast<TResult>(IEnumerable)

這個方法是幾個標準查詢運算符方法之一,可以套用至具有非參數化型別的集合,例如 ArrayList。 這是因為 OfType 會擴充 型別 IEnumerableOfType 不能只套用至以參數化 IEnumerable<T> 型別為基礎的集合,但以非參數化 IEnumerable 型別為基礎的集合也一併套用。

藉由套用 OfType 至實作 的 IEnumerable集合,您可以使用標準查詢運算符來查詢集合。 例如,指定的型別自變數ObjectOfType傳回 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