tags:

views:

223

answers:

2

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?

+11  A: 

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.

Adam Robinson
It isn't related to this specific question, but if the enumerator is disposable, it will get disposed too.
Marc Gravell
@Marc: Thanks! Edited; I forgot about that
Adam Robinson
Hi,In that case, which code is better of the two,for(int i = 0; i < StudentArray.Length; studentArray++){}
Siddharth
Hi, In that case, which code is better of the two, for(int i = 0; i < StudentArray.Length; studentArray++) { // do something } of int count = StudentArray.Length;for(int i = 0; i < count ; studentArray++) { // do something }
Siddharth
I'm assuming you meant i++ in there, not studentArray++. Anyway, there would theoretically be an advantage toward the latter, but I doubt you'd ever see it. Just stick with the simple approach and do the first.
Adam Robinson
+4  A: 

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.

allgeek