How to: Query an ArrayList with LINQ (C#)

When using LINQ to query non-generic IEnumerable collections such as ArrayList, you must explicitly declare the type of the range variable to reflect the specific type of the objects in the collection. For example, if you have an ArrayList of Student objects, your from clause should look like this:

var query = from Student s in arrList  
...  

By specifying the type of the range variable, you are casting each item in the ArrayList to a Student.

The use of an explicitly typed range variable in a query expression is equivalent to calling the Cast method. Cast throws an exception if the specified cast cannot be performed. Cast and OfType are the two Standard Query Operator methods that operate on non-generic IEnumerable types. For more information, seeType Relationships in LINQ Query Operations.

Example

The following example shows a simple query over an ArrayList. Note that this example uses object initializers when the code calls the Add method, but this is not a requirement.

using System;  
using System.Collections;  
using System.Linq;  

namespace NonGenericLINQ  
{  
    public class Student  
    {  
        public string FirstName { get; set; }  
        public string LastName { get; set; }  
        public int[] Scores { get; set; }  
    }  

    class Program  
    {  
        static void Main(string[] args)  
        {  
            ArrayList arrList = new ArrayList();  
            arrList.Add(  
                new Student  
                    {  
                        FirstName = "Svetlana", LastName = "Omelchenko", Scores = new int[] { 98, 92, 81, 60 }  
                    });  
            arrList.Add(  
                new Student  
                    {  
                        FirstName = "Claire", LastName = "O’Donnell", Scores = new int[] { 75, 84, 91, 39 }  
                    });  
            arrList.Add(  
                new Student  
                    {  
                        FirstName = "Sven", LastName = "Mortensen", Scores = new int[] { 88, 94, 65, 91 }  
                    });  
            arrList.Add(  
                new Student  
                    {  
                        FirstName = "Cesar", LastName = "Garcia", Scores = new int[] { 97, 89, 85, 82 }  
                    });  

            var query = from Student student in arrList  
                        where student.Scores[0] > 95  
                        select student;  

            foreach (Student s in query)  
                Console.WriteLine(s.LastName + ": " + s.Scores[0]);  

            // Keep the console window open in debug mode.  
            Console.WriteLine("Press any key to exit.");  
            Console.ReadKey();  
        }  
    }  
}  
/* Output:   
    Omelchenko: 98  
    Garcia: 97  
*/  

See Also

LINQ to Objects (C#)