现在的位置: 首页 > 综合 > 正文

使用Enumerable.OfType扩展方法实现非泛型集合的Linq查询

2012年11月01日 ⁄ 综合 ⁄ 共 716字 ⁄ 字号 评论关闭

  Linq查询运算符设计用于任何实现了IEnumerable<T>接口的类型。但System.Collections中传统的非泛型容器类未实现IEnumerable<T>接口,在这些非泛型容器上怎样执行Linq查询呢?

  我们可以使用扩展方法Enumerable.OfType<T>()扩展方法将非泛型容器转换为IEnumerable<T>类型后,再执行查询。Enumerable.OfType<T>扩展方法的原型为:

      public static IEnumerable<T> OfType<T>(this IEnumerable source);

  示例代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace TestVar
{
class Program
{
static void Main(string[] args)
{
//创建整型数组
ArrayList intAry = new ArrayList { 1, 2, 3, 4, 5, 6 };
//将其转换为泛型容器
IEnumerable<int> intEnumable = intAry.OfType<int>();

//使用强类型立即获取查询结果
List<int> intList = (from x in intEnumable
where x % 2 == 0
select x).ToList();

//输出查询结果
foreach (int v in intList)
{
Console.Write(v.ToString()
+ " ");
}

Console.ReadKey();
}
}
}

抱歉!评论已关闭.