2

As per title, i need to create a method in C#/.NET 4 that can jumble the order a XPathNodeIterator object. The method needs to loop though all the child items ("/*") to randomly reorder the children.

I need some help to some to get started - All i have is the method stub:

public XPathNodeIterator RandomizeXPathNodeIterator(XPathNodeIterator iterator)

Any help is appreciated! Thanks

atp03
  • 3,539
  • 3
  • 17
  • 20
  • Which .NET version do you target? – Martin Honnen Oct 22 '12 at 12:14
  • 1
    Get the count of the selected nodes: `count(YourExpression)` Let this be `N`. Then in C# generate a random sequence of distinct integers from 1 to N (this isn't an XPath problem, despite the fact that it can be done using XSLT). Then iterate the iterator and keep count of the current position of the iterator. Populate an array (List) of nodes, so that the current node occupies the respective array position, which is the position in the random sequence, for which its value is the position of the current node in the iterator. – Dimitre Novatchev Oct 22 '12 at 12:40

1 Answers1

0

You can iterate XPathNodeIterator as:

    XPathNavigator[] positions = new XPathNavigator[iterator.Count];
    int i = 0;

    while (iterator.MoveNext())
    {
        XPathNavigator n = iterator.Current;
        positions[i] = n;

        i++;
    }

Then, scrumble the array

L.Grillo
  • 960
  • 3
  • 12
  • 26
  • How do i returrn XPathNavigator[] positions as XPathNodeIterator? – atp03 Oct 22 '12 at 14:38
  • `XPathNodeIterator` is an abstract class, if you really want or need your method to return an `XPathNodeIterator` then you will have to extend that abstract class by your own concrete implementation that overrides the abstract methods and properties (e.g. `Count`, `Current`, `MoveNext` ...). Then your method can create an instance of the concrete implementation and return it. – Martin Honnen Oct 22 '12 at 15:29