Friday, November 27, 2009

XLINQ and Lambda Expressions

I had used LINQ recently in one of the projects but I had very less knowledge while developing it. But I am sure it is one of the very good add on for the programming which makes many of our life so easy especially while working with xml and DB. Most of the places I had used the LINQ query but I just tried using the same thing using the Lambda expressions.

If you are new to XLINQ, you might want to go through xlinq first. I take an example as below and explain how to obtain the same results using XLINQ and Lambda expressions.

My xml
string xmldoc = "<customer><item id=\"1\" status=\"N\" name=\"Item 1\"><item id=\"2\" status=\"O\" name="Item 2\"><item id=\"3\" status=\"O\" name=\"an item\"></customer>";

Loading xml to Xelement
XElement objElement = XElement.Parse(xmldoc);

Ok now my xml is loaded and ready to use. Lets say if I need to take the items with Status “O” and order by Name, if we have to do it using XMLDocument(in earlier version) it would require many lines of code and debugging. The LINQ made it very easy. I would simply query as below

IEnumerable oldItem = (from c in objElement.Elements("Item")
where (string)c.Attribute("Status") == "O"
orderby c.Attribute("Name").Value
select c);

The oldItem list will have all the items with Status “O” order by “Name”. Just parse through oldItem and you will know it for sure

foreach (XElement obj in oldItem)

Now let’s do the same thing using lambda expression

IEnumerable oldItemLamda = objElement.Elements("Item").Where(d => d.Attribute("Status").Value == "O").OrderBy(d => d.Attribute("Name").Value);

It looks pretty straitght forward while the above looks like someone needs to have query skill. The expression d => d.Attribute("Status").Value == "O" is the predicate. Have you observed the new operator used here ? "=>" is called as Lambda operator which is introduced in .net 3.0. The expression on right side is called lambda expression. An expression lambda returns the result of the expression and takes the following basic form:

(input parameters) => expression

So we have the Xelement filter with “O” status and Order by name. Lets make sure we have the right elements selected

foreach (XElement obj in oldItemLamda)

The results from the above query and the lambda expression are same.

There are many methods available which expects the predicate and returns the result based on the expression.

You can get more information on Lambda expression on

No comments:

Post a Comment