Enumerable.OfType)>) 方法

 

根据指定类型筛选 IEnumerable 的元素。

命名空间:  System.Linq
程序集:  System.Core(在 System.Core.dll 中)

 

此方法通过使用延迟执行实现。即时返回值为一个对象,该对象存储执行操作所需的所有信息。只有通过直接调用对象的 GetEnumerator 方法或使用 Visual C# 中的 foreach(或 Visual Basic 中的 For Each)来枚举该对象时,才执行此方法表示的查询。

OfType<(Of <(TResult>)>)(IEnumerable) 方法仅返回 source 中那些可以转换为 TResult 类型的元素。如果元素不能转换为 TResult 类型,但却不想接收异常,则使用 Cast<(Of <(TResult>)>)(IEnumerable)

此方法是少数标准查询运算符方法之一,标准查询运算符方法可应用于含有非参数化类型(如 ArrayList)的集合。这是因为 OfType<(Of <(TResult>)>) 扩展了类型 IEnumerableOfType<(Of <(TResult>)>) 不仅无法应用于基于参数化的 IEnumerable<(Of <(T>)>) 类型的集合,也无法应用于基于非参数化的 IEnumerable 类型的集合。

通过将 OfType<(Of <(TResult>)>) 应用于实现 IEnumerable 的集合,可以获得使用标准查询运算符查询集合的能力。例如,将 Object 的类型参数指定为 OfType<(Of <(TResult>)>) 将返回一个对象,其类型为 C# 中的 IEnumerable<Object>IEnumerable(Of Object) 中的 Visual Basic,标准查询运算符可应用于该对象。

C#代码:

ContractedBlock.gif ExpandedBlockStart.gif Code
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

 

转载于:https://www.cnblogs.com/qishichang/archive/2009/05/29/1491625.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值