Sidhartha Shenoy
Sidhartha Shenoy

Reputation: 179

for each loop iteration

Let us assume the code I use to iterate through a node list

foreach(XmlNode nodeP in node.SelectNodes("Property"))
{
  propsList.Add(nodeP.Attributes["name"].Value, true);
}

in this case does the expression node.SelectNodes("Property") , get evaluated during each iteration of for each or once?

Upvotes: 7

Views: 801

Answers (2)

Adam Robinson
Adam Robinson

Reputation: 185643

Only once. The foreach statement is syntactic sugar for (in your case)...

{
    IEnumerator<XmlNode> enumerator = node.SelectNodes("Property").GetEnumerator();

    XmlNode nodeP;

    while(enumerator.MoveNext())
    {
        nodeP = enumerator.Current;

        propsList.Add(nodeP.Attributes["name"].Value, true);
    }

    IDisposable disposable = enumerator as IDisposable;

    if(disposable != null) disposable.Dispose();
}

So the actual call to SelectNodes() only happens one time.

Upvotes: 11

allgeek
allgeek

Reputation: 259

It looks like you're asking about C# / .NET. The SelectNodes() call will be made once, and then the enumerator will be retrieved from the return value (which implements IEnumerable). That enumerator is what is used during the loop, no subsequent calls to SelectNodes() are necessary.

Upvotes: 4

Related Questions