LINQ Tips: Querying ArrayList via LINQ
Problem
If you try to query an ArrayList via LINQ you might be surprised to see that its not supported and throwing an exception. In other words the following query will not work at all.
ArrayList students = GetStudents();
var query =
from student in students
where student.Score > 80
select new { student.ID, student.Name };
Cause
The problem comes from the fact that LINQ to Objects has been designed to query generic collections that implement the System.Collections.Generic.IEnumerable<T> interface. Where an ArrayList is a nongeneric collection that contains a list of untyped objects and also does not implement IEnumerable<T>.
Solution
Cast operator comes into rescue.
Here is the signature of the Cast operator:
public static IEnumerable<T> Cast<T>(this IEnumerable source)
Cast can take a nongeneric IEnumerable and returns a generic IEnumerable<T>.
A modification of the above query like this will solve the problem and you will be able to query ArrayList via LINQ.
ArrayList students = GetStudents();
var query =
from student in students.Cast<Student>()
where student.Score > 80
select new { student.ID, student.Name };