I was working with some C# code today in the morning and I had something like:
foreach(DataRow row in MyMethod.GetDataTable().Rows) {
//do something
}
So, as I dont have a full understanding of the language framework I would like to know if GetDataTable() gets called each time an iteration is done or if it just gets called once and the resulting data (which would be Rows) is saved in memory to loop through it. In any case, I declared a new collection to save it and work from there...
I added a new variable so instead I did:
DataRowCollection rowCollection = MyMethod.GetDataTable().Rows;
foreach(DataRow row in rowCollection) {
//do something
}
But im not quite sure if this is necessary.
Thanks in advance.
The foreach loop in C# iterates items in a collection, like an array or a list. It proves useful for traversing through each element in the collection and displaying them. The foreach loop is an easier and more readable alternative to for loop.
The foreach statement: enumerates the elements of a collection and executes its body for each element of the collection. The do statement: conditionally executes its body one or more times.
Yes, foreach will call Dispose() on the enumerator if it implements IDisposable.
An iterator method or get accessor performs a custom iteration over a collection. An iterator method uses the yield return statement to return each element one at a time.
Don't worry about it; it'll only execute GetDataTable() once internally to get the enumerator object from the DataRowCollection, and then fetch a new item from it every run through the loop.
A foreach loop is only syntaxic sugar for
var enumerator = MyMethod.GetDataTable().Rows.GetEnumerator();
while (enumerator.MoveNext())
{
DataRow row = enumerator.Current;
// Initial foreach content
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With