Order By with LINQ to XML

posted in: Uncategorized | 0

BronwenWeeGo.jpgWas playing with Linq to XML today and wanted to do an orderby based on one of the fields in the xml file.

It’s a bit different to SQL as the orderby goes between the from and the select.

My code below shows selecting everything and ordering by the eventdate descending.

XDocument eventsXml = XDocument.Load(events.xml);
var temp = from feed in eventsXml.Descendants("LocalEvent")
           orderby Convert.ToDateTime(feed.Element("EventDate").Value) descending
           select new LocalEvent
               ID = Convert.ToInt32(feed.Element("ID").Value),
               EventDate = Convert.ToDateTime(feed.Element("EventDate").Value),
               EventDescription = feed.Element("EventDescription").Value,
               EventName = feed.Element("EventName").Value,
               Latitude = Convert.ToDouble(feed.Element("Latitude").Value),
               Longitude = Convert.ToDouble(feed.Element("Longitude").Value),
               Location = feed.Element("Location").Value

return temp.ToList();

kick it on DotNetKicks.com