rdrake
|
Posted: Wed Feb 27, 2008 10:56 pm Post subject: [C#] A Little Bit of LINQ |
|
|
Let's start off by answering a question I'm sure you're all wondering, what is LINQ? LINQ (or Language INtegrated Query, pronounced "link") is an extension to .NET languages which allows them to perform type-safe SQL-style queries on many types of data. For example, you can use LINQ to query XML, SQL, or other data sources.
In this case we want to parse the XML for the RSS feed Computer Science Canada Blog. Now we know feeds are composed of items, and those items hold certain information. In particular we're interested in the following information:
- Title of the post
- Link to the post
- Date and time of publication
- Who wrote it
- A brief description of what the post contains
So, let's get started by creating a class to hold all that data.
C#: | namespace LinqToBlog
{
class Item
{
public string Title { get; set; }
public string Link { get; set; }
public System.DateTime PublicationDate { get; set; }
public string Description { get; set; }
}
} | Great, everything appears to be there (except the Author field, I'll get to that).
Now that we have an object to store the data in, let's go on and start writing the query. Each item object is created from the contents of what else but the <item> XML tag. So we want to select all the children of the item tags in our query.
C#: | var doc = XDocument.Load(@"http://feeds.feedburner.com/ComputerScienceCanadaBlog?format=xml");
var results = from result in doc.Descendants("item")
select result; | The above probably looks a bit confusing, I'll do my best to explain it. The first line is used to load the XML document from its original home on the web into an XDocument object in memory. This URI which specifies the file to load can be either local, in a memory stream (ie. over another network protocol), or remote.
The second line is where the magic happens. We pull out all the objects from the loaded document and return all the objects it finds.
Now we can iterate through all the items we've found, create a new object, than display it to the user. C#: | foreach (var n in results )
{
var item = new Item ()
{
Title = n. Element("title"). Value,
Link = n. Element("link"). Value,
Comments = n. Element("comments"). Value,
PublicationDate = DateTime. Parse(n. Element("pubDate"). Value),
Description = n. Element("description"). Value,
};
Item. Items. Add(item );
Console. WriteLine(item. ToString());
Console. WriteLine("----------");
} | Here all we're doing is creating a new item object and initializing its properties using the XML elements which were returned from the LINQ expression above. We go through all the objects returned, pull out the element based on its name, then extract its value and assign it to its respective property.
Now the readers who were closely paying attention may wonder where this "Item.Items.Add(item);" line came from. In order to make this data useful at all, we need to store it in an object for easier retrieval later on. Thus we should add a static list of type Item to the Item class. The following is the completed Item.cs file:
C#: | using System. Collections. Generic;
namespace LinqToBlog
{
class Item
{
private static List<Item> _Items = new List<Item> ();
public string Title { get; set; }
public string Link { get; set; }
public string Comments { get; set; }
public System. DateTime PublicationDate { get; set; }
public string Description { get; set; }
public static List<Item> Items
{
get { return _Items; }
set { _Items = value; }
}
public override string ToString ()
{
return this. Title + "\nPublished on " + this. PublicationDate. ToString() + "\n" + this. Link;
}
}
} | You'll notice that I have also overridden the ToString() method in order to output the items in a nicer way to the user.
Putting the rest together, here is the completed Program.cs file:
C#: | using System;
using System. Linq;
using System. Xml. Linq;
namespace LinqToBlog
{
class Program
{
static void Main (string[] args )
{
var doc = XDocument. Load(@ "http://feeds.feedburner.com/ComputerScienceCanadaBlog?format=xml");
var results = from result in doc. Descendants("item")
select result;
foreach (var n in results )
{
var item = new Item ()
{
Title = n. Element("title"). Value,
Link = n. Element("link"). Value,
Comments = n. Element("comments"). Value,
PublicationDate = DateTime. Parse(n. Element("pubDate"). Value),
Description = n. Element("description"). Value,
};
Item. Items. Add(item );
Console. WriteLine(item. ToString());
Console. WriteLine("----------");
}
}
}
} | A note about the authors section: Unfortunately the tag which specifies the creator's name belongs to a different namespace than the rest of the object. I have yet to figure out a way to get this to work properly to be honest.
You compile the above code files with the C# 3.5 compiler which should be located in C:\Windows\Microsoft.NET\Framework\v3.5 for most people. This should work:
code: | C:\Windows\Microsoft.NET\Framework\v3.5\csc.exe /out:LinqToBlog.exe Item.cs Program.cs | Also, feel free to admire my wit with regards to naming the output file.
This should be the result:
It's just that easy!
Description: |
|
Filesize: |
20.39 KB |
Viewed: |
118 Time(s) |
|
|
|
|