简体   繁体   中英

How many times is the list of objects retrieved in a C# foreach loop?

I typically try to store the array/collection as a local variable before running a foreach loop: as opposed to calling the Get function inside of foreach. This is because I assume that it will have to fetch that array on each iteration of the loop, and I would rather it only have to get the array/collection one time. I'm having trouble finding documentation to support my theory, so I wanted to ask the gurus.

//Assume that FindStringsContaining() is a CPU
//intensive operation. Does it run only once?
foreach(string data in FindStringsContaining("Data"))
{
    //use the data
}

It will always run exactly once .

Foreach operates on an IEnumerable , and simply iterates over the collection; executing the code inside the loop for each item it finds.

Note that modifying the collection during enumeration (which would potentially require a re-enumeration) is explicitly not allowed (an InvalidOperationException will be thrown).

The method call would only happen once. It then returns an IEnumerable<string> which is iterating over in a streaming fashion (calling the MoveNext method while items remain in the collection or a break isn't hit).

It is called once. A quick way to verify this is to place a breakpoint inside your FindStringsContaining() method, and you can see it is only hit once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM