Saturday, October 11, 2008

Power of LINQ - Querying ArrayLists

Hey all!

Welcome back :)

This posting is about querying ArrayLst's using LINQ. Following is an example of the same. Explanations follow after the code..

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

namespace QueryArrayList
{
public class Report
{
public int reportNo;
public string reportName;
}

public class QueryArrayList
{
private static bool found = false;

public QueryArrayList()
{
}

public static void Main(string[] args)
{
string query_text = "null";

if (args.Length == 1)
{
query_text = args[0];
}

ArrayList aList = new ArrayList();

for (int i=0; i < 10; i ++)
{
Report report = new Report();
report.reportNo = i;
report.reportName = "Report " + i.ToString();

aList.Add(report);
}

var query =
(from Report reportList in aList
where reportList.reportName.Contains(query_text)
select new { reportList });

if (query != null)
{
foreach (var report in query)
{
Report rpt = new Report();
rpt.reportNo = report.reportList.reportNo;
rpt.reportName = report.reportList.reportName;

Console.WriteLine("Report retrieved: Report Number: {0} and Report Name: {1}",rpt.reportNo,rpt.reportName);

found = true;
}
}

if (! found)
Console.WriteLine("Empty result set");
}
}
}


The code is pretty straight forward. So I will get into the LINQ related part directly. There is a class called Report and the class QueryArrayList creates 10 objects of Report. The following LINQ query takes in as a parameter some text that is used to select a set of reports containing that text.

var query = (from Report reportList in aList
where reportList.reportName.Contains(query_text)
select new { reportList });


Here 'aList' is the ArrayList that contains the list of "Report" objects and using this part

from Report reportList

we specify that we are querying an ArrayList of type "Report".

where reportList.reportName.Contains(query_text)

The above part is to limit rows with the query text and finally

select new { reportList }

is to select the reports satisfying the condition and place it in a variable called reportList

In the foreach part I get each row in the set, create a new object of type "Report" and print it to the console.

That's it! We have successfully queried an ArrayList!!

Happy coding :)

No comments: