您的位置:首页 > 其它

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

2011-04-05 21:34 1131 查看
  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();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐