Saturday, September 20, 2008

A little flavour of LINQ

LINQ, Language INtegrated Query is a new programming feature that's integrated with the new release of Visual Studio 2008. I've been really fancy about the creation of LINQ. Actually it is a language that tried to gap between different datasources such as XML, Object, Database and Dataset using a Simple to understand SQL query like language. I'm playing around with querying XML data using LINQ at my work for my web service project since I'm dealing with alot of transformation between XML, Object and Database in my project. I need to download XML string from my web service. Then need to insert XML data into Database and later retrieve data from database into our programming language to use as data for my objects. So LINQ naturally become one of my choice. I just want to share a little on how easy it was to parse an XML using LINQ. For example I got the XML file with the data below

<contacts>
<contact contactId="2">
<firstName>Leo</firstName>
<lastName>Lu</lastName>
<phone>91234567</phone>
<age>26</age>
</contact>
<contact contactId="3">
<firstName>James</firstName>
<lastName>Ng</lastName>
<phone>61234567</phone>
<age>32</age>
</contact>
......
</contacts>

Imagine the above XML list with lots of contacts. And I want to find my particular using LINQ, this is how I have to query it

var xmlSource = contacts.Load(@"../../Contacts.xml"); //load your xml file

// This query will search user from my XML file where first name is equal Leo and select the first name and last name together
var query = from c in xmlSource.contact
where c.firstname.value = "Leo"
select c.firstName + " " + c.lastName;


foreach(string name in q)
Console.WriteLine("Customer name = {0}", name);

Output will be

Customer name = Leo Lu

How cool is that? If you do the XML parsing before, it is not very intuitive previously and most probably you may need a few loops and if statement if you have a number of things to filter out. WIth LINQ, querying effort is much simplified.

No comments: