Sort IENumerable after DateTime

I have the following

var path = HttpContext.Current.Server.MapPath("~/App_Data/WorldNews.xml");
        var feedXml = XDocument.Load(path);


        IEnumerable<NewsItem> feeds = from feed in feedXml.Descendants("item")
                    select new NewsItem
                    {
                        Title = feed.Element("title").Value,
                        Link = feed.Element("link").Value,
                        Description = Regex.Match(feed.Element("description").Value, @"^.{1,180}\b(?<!\s)").Value,
                        Date = Convert.ToDateTime(feed.Element("pubDate").Value)

                    };

How can I sort this after "Date"?

Upvotes: 0

Views: 1007

Answers (1)

recursive
recursive

Reputation: 86064

You could use let to store the converted dates.

IEnumerable<NewsItem> feeds = 
    from feed in feedXml.Descendants("item")
    let date = Convert.ToDateTime(feed.Element("pubDate").Value)
    orderby date
    select new NewsItem
    {
        Title = feed.Element("title").Value,
        Link = feed.Element("link").Value,
        Description = Regex.Match(feed.Element("description").Value, @"^.{1,180}\b(?<!\s)").Value,
        Date = date
    };

To sort it after creating, you can do this.

feeds = feeds.OrderBy(f => f.Link).ToArray();

The reason I added .ToArray() is that without it, you'll be instantiating a chain of queries, each of which gets more and more expensive to calculate, and goes back to xml parsing each time.

Upvotes: 1

Related Questions