咱們都知道,Linq能查詢泛型集合,確切的說是:LINQ能實現查詢泛型對象或者實現了IEnumerable。可是,很遺憾的是諸如ArrayList這樣的非泛型集合並無實現IEnumerable。那咋辦呢?總不能把這麼絢麗的Linq技術對非泛型關上大門把!~其實,方法仍是有的。spa
場景還原:code
定義一個car的類:對象
class Car { public int CurrentSpeed; public int MaxSpeed; public string PetName; }
對ArrayList 裝載一些數據:blog
ArrayList cars = new ArrayList(); cars.Add(new Car { CurrentSpeed = 21, MaxSpeed = 2, PetName = "aa" }); cars.Add(new Car { CurrentSpeed = 212, MaxSpeed = 22, PetName = "aa1" });
若是強制使用Linq操做,會報錯:string
解決方法以下:ast
var myAllCars = cars.Cast<Car>(); var result = from c in myAllCars where c.MaxSpeed > 10 select c;
var myAllCars = cars.OfType<Car>(); var result = from c in myAllCars where c.MaxSpeed > 10 select c;
OfType 除了上面轉換非泛型以外,還有一個功能是刷選數據的功能。class
這個很簡單泛型