Code Refining

September 28th, 2009 admin Posted in .NET Programming, LINQ No Comments »

While refining the XML parsing code on our site I've managed to squeeze down what was 60 lines of code into its semantic minimum as I use more and more LINQ in C#.

While I wont post the old code (for obvious reasons) here is the new code. It simply takes the weekly XML RSS feed from WatchGuard and outputs the top ten stories to the website in the Accordion control.

From 60, to 6. Code highlighting throws a tissy when introducing lambda expressions so here is the code sans code highlighting.

  1.  
  2. XElement xml = XElement.Load(Server.MapPath("~/library/xml/") + "news.xml");
  3. var titles = from item in xml.Element("channel")
  4. .Elements("item").Take(8) select item;
  5. Array.ForEach(titles.ToArray(), p =>
  6. {
  7. Response.Write("p.Element("link").Value + p.Element("title").Value);
  8. });
  9.  

I had to remove the HTML formatting as I just didn't want to fight with WordPress/Code Highlighting anymore but you get the general idea.