Technical Fun

First Encounter of the LINQ Kind

Posted on: December 19, 2007

I got an XML document that looks like this.

<Area id=”1″>
<name>Brave Land</name>
<description>An area where the brave may live forever</description>

Now, if I want to search and fetch the text inside the “name” tag based on a supplied “id”, I can rely faithfully on LINQ.

XDocument doc = XDocument.Load(PATH_TO_XML_DOCUMENT);
var x = from area in doc.Descendants(“Area”)
          where (int)area.Attribute(“id”) == MY_SUPPLIED_ID
          select (string)area.Element(“name”);

and consume it using x.First()

aaah …. how readable, how lovely, Nirvana!!!


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: