May 30, 2011

How to query an ArrayList with LINQ

In this example, I will show how to query an ArrayList using Linq. Since ArrayList are non-generic IEnumerable collections, the type of variable in the collection must be explicitly declared in the linq query.

I already have a web application setup, so, I will just add a class called Person. This is a very simple class containing only 2 properties – FirstName and LastName. The code for the class is below.

Person Class
  1. namespace WebApplication1.CSClass
  2. {
  3.     public class Person
  4.     {
  5.         public string FirstName { get; set; }
  6.         public string LastName { get; set; }
  7.  
  8.         public override string ToString()
  9.         {
  10.             return FirstName + " " + LastName;
  11.         }
  12.     }
  13. }

I will then add a web form where I will add an ArrayList, add Person objects to the collection and then query the collection using Linq. The code for this is below.

Query ArrayList with LINQ
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. using System.Collections;
  8. using WebApplication1.CSClass;
  9.  
  10. namespace WebApplication1
  11. {
  12.     public partial class LinqText : System.Web.UI.Page
  13.     {
  14.         protected void Page_Load(object sender, EventArgs e)
  15.         {
  16.             GetList();
  17.         }
  18.  
  19.         private void GetList()
  20.         {
  21.             ArrayList list = new ArrayList();
  22.             list.Add(new Person { FirstName = "Scooby", LastName="Doo" });
  23.             list.Add(new Person { FirstName = "Bugs", LastName = "Bunny" });
  24.             list.Add(new Person { FirstName = "Peter", LastName = "Pan" });
  25.  
  26.             var q = from Person p in list
  27.                     orderby p .FirstName
  28.                     orderby p.LastName
  29.                     select p;
  30.  
  31.             string br = "<br/>";
  32.             foreach (Person p in q)
  33.             {
  34.                 L1.Text += p.ToString() + br;
  35.             }
  36.  
  37.         }
  38.     }
  39. }

Note that, in the linq query, the object type is specified. The query will not work unless it is specified.

0 comments: