Example for LINQ Query to ArrayList in C#

In the past I have described some topics on the LINQ over XML such as: generate xml document with elements and attributes using linq to xml, create the xml document using linq to xml in c# and UPDATE THE XML FILE USING LINQ IN C#. This time we will perform some LINQ query over the ArrayList object in the C#.

ArrayList is the non generic collection so you must explicitly declare the type of the range variable to reflect the specific type of the objects in the collection. The exception InvalidCastException will be occurs when the type mismatch.

The following example demonstrates the use of the simple LINQ query to print the numbers that are greater than 35.

ArrayList arrList = new ArrayList();
arrList.Add(45);
arrList.Add(69);
arrList.Add(30);
arrList.Add(50);
 
var query = from int num in arrList 
            where num > 35
            select num;
foreach (int num in query)
    {
        Console.WriteLine(num);
    }

The result of the above program will be
45
69
50

The arrList contains the integer type values so you must use int type in the from clause like as:

from int num in arrList

The var query contains only the command and program doesn’t start the execution immediately. Execution starts in the for each statement, this execution is also called as deferred execution of the LINQ.

If the declare type in the from clause does not match the type of the objects in the arrList, the ‘System.InvalidCastException: Specified cast is not valid’ error will be occur.

2 thoughts on “Example for LINQ Query to ArrayList in C#”

Comments are closed.