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 Eachforeach Visual Basic 中使用 来枚举对象之前,不会执行此方法表示的查询。

方法 OfType<TResult>(IEnumerable) 仅返回中 source 非 null 且与类型 TResult兼容的元素。 若要在元素无法强制转换为类型 TResult时接收异常,请使用 Cast<TResult>(IEnumerable)

此方法是少数可应用于具有非参数化类型的集合(如 )的标准查询运算符方法之一 ArrayList。 这是因为 OfType 扩展类型 IEnumerableOfType 不能仅应用于基于参数化 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