Geeks With Blogs

News Awarded Microsoft MVP C#.NET - 2007, 2008 and 2009


I am born in Bangladesh and currently live in Melbourne, Australia. I am a Microsoft Certified Application Developer MCAD Chartered Member (C# .Net)and born in Bangladesh.
I am founder and Chief Executive Officer of
Simplexhub, a highly experienced software development company based in Melbourne Australia and Dhaka, Bangladesh. Co-founder and core developer of Pageflakes www.pageflakes.com.
Simplexhub, is on its mission to build a smart virtual community in Bangladesh and recently launched beta realestatebazaar.com.bd an ASP.NET MVC application written in C#.NET.


Some of 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
Shahed Khan blog

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

Posted on Tuesday, February 5, 2008 4:30 PM | Back to top


Comments on this post: LINQ Tips: Querying ArrayList via LINQ

# re: LINQ Tips: Querying ArrayList via LINQ
Requesting Gravatar...
Very usefyl tip. Have to keep in mind :)
Left by Shreedhar on Sep 26, 2008 7:54 PM

Your comment:
 (will show your gravatar)


Copyright © Shahed Khan | Powered by: GeeksWithBlogs.net