Geeks With Blogs
Max's Blog .NET, Windows Phone, SQL Server and other exciting stuff

It looked like we should look a bit about LINQ fundamentals before we actually get into the core programming for our Silverlight twitter application. So we’ll look into LINQ for a few more posts, then we will proceed with our usual Silverlight stuff.

Line INtegrated Query allows us to use Query language to select data from almost any type of data sources like XML, SQL, Objects, etc.... For more information about LINQ, visit this page, I don’t want to get deep into the details.

You can get the sample XML files I’ve used in this part is

. Or you get it from http://msdn.microsoft.com/en-us/library/ms762271(VS.85).aspx. Go through this xml document, it will help in better understanding.

Now let us quickly get into some hands on coding stuff.

1) Create a new console application C# project and add the book.xml to it. Now your sol. explorer should look something like this

LINQProject

2) You are now going to load a xml document into a XDocument type variable like this

XDocument xmlDoc = XDocument.Load(@"C:\Users\Max\Documents\Visual Studio 2008\Projects\XMLLINQ\XMLLINQ\books.xml");
 
Now you have the xml document in xmlDoc variable and now on we’ll be querying against this variable.

3) Now I am going to find out all the books with “Computer” as the genre. Which can be queried as below:

//The actual query, where we choose all the books that are of "Computer" genre.
var query = from p in xmlDoc.Elements("catalog").Elements("book")
where (string)p.Element("genre") == "Computer"
select p;
 
4) Then the next step is to iterate through this and print out the desired values.
 
5) Then I am going to use the variable query from step 3 to find out how many Computer genre books are priced more than 40. This can be done using the query below.
 
var query2 = from p1 in query
where Convert.ToDouble(p1.Element("price").Value) > 40.00
select p1;

5) The final      is here for your reference. The output should be
 
Capture
 
We will look into LINQ for SQL, group by and sort queries in next post. Please post leave your comments below.
 

Technorati Tags: ,
Posted on Thursday, December 3, 2009 8:59 PM LINQ | Back to top


Comments on this post: LINQ Part 1 – LINQ for XML

# re: LINQ Part 1 – LINQ for XML
Requesting Gravatar...
Hello its very helpful to me ,but please provide .cs code also, that link is not working,thanks
Left by praveen on Jan 02, 2012 8:33 PM

Your comment:
 (will show your gravatar)


Copyright © Max | Powered by: GeeksWithBlogs.net