posts - 218, comments - 222, trackbacks - 68

My Links

News




I am a Microsoft Certified Application Developer MCAD Chartered Member (C# .Net) and born in Bangladesh.
I work for Ocean Informatics Pty Ltd as a Senior Developer - Analyst.
I am also co-founder and core developer of Pageflakes (acquired by LiveUniverse) www.pageflakes.com
and most recently created SmartCodeGenerator

My Articles
Flexible and Plugin based .Net Application..
Mass Emailing Functionality with C#, .NET 2.0, and Microsoft® SQL Server 2005 Service Broker'
Write your own Code Generator or Template Engine in .NET
Smart Code Generator .NET: Usage Overview
Smart Code Generator .NET: Architectural Overview
Smart Code Generator .NET: using with NAnt and Cassini

Archives

Free Programming Language Training

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 };

Print | posted on Tuesday, February 05, 2008 4:30 PM |

Feedback

Gravatar

# re: LINQ Tips: Querying ArrayList via LINQ

Cool tip, sure comes handy! Thx for sharing.
2/10/2008 4:27 AM | jason
Gravatar

# re: LINQ Tips: Querying ArrayList via LINQ

Very usefyl tip. Have to keep in mind :)
9/26/2008 7:54 PM | Shreedhar

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 3 and 1 and type the answer here:

Powered by: