Linq之查询非泛型集合

Linq to object 中我们经常可以很方便的查询多种集合比如List<T>泛型,主要的原因是他们都实现了System.Collections.Generic.IEnumerable<T>接口从而可以完成相关的查询操作但并非所有的类都实现了以上接口比如说System.Collections.ArrayList,那么通过以下三种方式可以解决。

一、OfType操作符
先看它的签名 public static IEnumerable<TResult> OfType<TResult>( this IEnumerable source)根据指定类型筛选IEnumerable的元素,当source为null返回ArgumentNullException

var q  =  cars.OfType < Car > ().Where(c => c.Doors == 2 );


二、Cast强制转换
从Cast的签名就知道它可以返回IEnumerable<T> ,
public static IEnumerable<T> Cast<T>(this IEnumerable source)
但是也要注意,如果被转换的类型中不能被转为T的则会报Invalid-
CastException异常,如果是null的话则为NullReferenceException上面代码改写为:

var q  =  from c  in  cars.Cast<Car>
        
where  c.Doors == 2
        select 
new   {c.Name}


三、明确的类型定义
定义from中的查询类型,如

var q 
=  from Car c  in  cars
        
where  c.Doors= = 2
        select 
new   {c.Name}


你可能感兴趣的:(LINQ)