Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for each loop iteration

Tags:

c#

enumeration

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?

like image 724
Sidhartha Shenoy Avatar asked Apr 08 '09 13:04

Sidhartha Shenoy


2 Answers

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.

like image 73
Adam Robinson Avatar answered Oct 02 '22 20:10

Adam Robinson


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.

like image 44
allgeek Avatar answered Oct 02 '22 20:10

allgeek