筛选的元素 IEnumerable 根据指定的类型。
程序集: System.Core(位于 System.Core.dll)
参数
- source
-
Type:
System.Collections.IEnumerable
IEnumerable 要筛选其元素。
类型参数
- TResult
-
筛选序列元素所根据的类型。
此方法实现通过使用延迟的执行。 最接近的返回值是指存储执行的操作所需的所有信息的对象。 此方法所表示的查询不执行之前调用枚举的对象及其GetEnumerator 方法直接或通过使用 foreach 中 Visual C# 或 For Each 中 Visual Basic。
OfType<TResult>(IEnumerable) 方法只返回这些元素在 source 均可转换为类型 TResult。 若要改为收到的异常,如果元素不能转换为键入TResult, ,使用 Cast<TResult>(IEnumerable)。
此方法是可以应用于具有非参数化类型,如集合的几个标准查询运算符方法之一 ArrayList。 这是因为 OfType<TResult> 扩展类型 IEnumerable。OfType<TResult> 不能仅应用于所基于的集合参数化 IEnumerable<T> 类型,但基于非参数化的集合 IEnumerable 还需要键入。
通过应用 OfType<TResult> 到一个集合,其中实现 IEnumerable, ,您能够通过使用标准查询运算符查询的集合。 例如,如果指定的类型实参Object 到 OfType<TResult> 将返回类型的对象 IEnumerable<Object> 在 C# 或 IEnumerable(Of Object) 中 Visual Basic, ,将要应用的标准查询运算符。
下面的代码示例演示如何使用 OfType<TResult> 来筛选的元素 IEnumerable。
System.Collections.ArrayList fruits = new System.Collections.ArrayList(4); fruits.Add("Mango"); fruits.Add("Orange"); fruits.Add("Apple"); fruits.Add(3.0); fruits.Add("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.ToLower().Contains("n")); 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