0

In C#, I sorted an RSS feed using XpathExpression and a self defined compare function for the field Publication Date.

I need to convert this sorted XPathNodeIterator object to a List<XElement> 'Generic Linq type' object. I've tried to use an intermediary data-type but did not have any luck.

Tried:

List<XElement> elements = new List<XElement>();
IEnumerable<XElement> sortedElements;
IEnumerable<XElement> newElements;

sortedElements = (IEnumerable <XElement>) iterator;

I've also tried using order by on the list but that was unsuccessful using only List<XElement>.

NoWar
  • 36,338
  • 80
  • 323
  • 498
C-Jay
  • 11
  • 4

2 Answers2

1

Since this is an IEnumerable, the easiest way to convert to an IEnumerable<> is to use OfType, like this:

var sortedElements = iterator.OfType<XPathNavigator>();

This will not give you XElement objects; that's part of a separate XML API. However, the XPathNavigator objects may have the data you need, so you can follow up with some sort of Select depending on what you need:

var elementValues = iterator.OfType<XPathNavigator>().Select(n => n.Value);

If you do want to use System.Linq.Xml stuff, you may be able to rewrite your XPath as LINQ on an XDocument instead.

Jacob
  • 77,566
  • 24
  • 149
  • 228
  • Unfortunately I cannot use XPathNavigator. I have to rewrite my sort function. 'var doc = XDocument.Load(url);' 'elements.AddRange(doc.XPathSelectElements(_xpath).ToList()); ' that is how the List is being generated. Not my code and cannot be changed. I will have to run a sort compare method or new sort function. But I am unfamiliar with Linq. – C-Jay Apr 17 '15 at 15:37
  • if I use 'sortElement = elements.OrderBy(element => element.Element("pubDate").Value);' I get an error Cannot implicitly convert type 'System.Linq.IOrderedEnumerable' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast? – C-Jay Apr 17 '15 at 15:43
  • You must be assigning the value to a `List`. If you really _need_ it to be a list, you can add a `.ToList()` after your `.OrderBy()`. – Jacob Apr 17 '15 at 15:58
  • Thank you. That seemed to get rid of the error. Yes unforntunately it has to be a list. OrderBy did not sort the list. This I am guessing is because the actual value of pubDate is a string Fri, DD Month YYYY HH:MM:SS -XXXX. And typecasting to an int would be invalid and incorrect. – C-Jay Apr 17 '15 at 16:07
0

I know this question is old, but have you checked whether this works?

var xmlStrings = iterator.OfType<XPathNavigator>().Select(n => n.OuterXml).ToList();
var xmlElements = new List<XElement>();
xmlStrings.ForEach(el => xmlElements.Add(XElement.Parse(el)));
mstaal
  • 590
  • 9
  • 25