Daniel Cazzulino's Blog : Cursor-style iteration pattern

Cursor-style iteration pattern

The usual enumeration pattern in .NET is either of these:

foreach (string value in values)
{
  // do something.  
}

// or
for (int i = 0; i < values.Length; i++)
{
  string value = values[i];
  // do something.
}

When working with cursor-style APIs like the XmlReader or XPathNavigator, the pattern usual becomes something like this (note this is the same code for both APIs):

if (nav.MoveToFirstAttribute())
{
  do
  {
    // Do something with nav.Current.
  } while (nav.MoveToNextAttribute();
}

This is not as readable or compact as the usual approach. One solution to get back the for style of iteration, which I use all the time, is the following:

for (bool go = nav.MoveToFirstAttribute(); go; go = nav.MoveToNextAttribute())
{
  // Do something with nav.Current.
}

With this approach, you can the usual iteration pattern again, and have more compact and readable code. It can be used with all XPathNavigator methods that use MoveToFirst/MoveToNext:

// To process namespaces
for (bool go = nav.MoveToFirstNamespace(XPathNamespaceScope.Local); go; 
  go = nav.MoveToNextNamespace(XPathNamespaceScope.Local))
{
}

// To process all child elements of current
for (bool go = nav.MoveToFirstChild(); go; go = nav.MoveToNext())
{
}

posted on Monday, July 12, 2004 12:17 PM by kzu