I have a foreach which calls a method to get its collection.
foreach(var item in GetItemDetails(item))
{
}
Visual studio doesn't complain about this, nor does Resharper, however, before I continue to use this approach, I want to reach out and check if it is a recommended approach.
JavaScript Array forEach() The forEach() method calls a function for each element in an array. The forEach() method is not executed for empty elements.
The forEach() method calls a specified callback function once for every element it iterates over inside an array.
The forEach method passes a callback function for each element of an array together with the following parameters: Current Value (required) - The value of the current array element. Index (optional) - The current element's index number. Array (optional) - The array object to which the current element belongs.
There's nothing wrong with that. The method will only be evaluated once.
It is basically:
using(var iter = GetItemDetails(item).GetEnumerator())
{
while(iter.MoveNext()
{
var item = iter.Current;
// ...
}
}
There's nothing wrong with it.
Just two suggestions:
If what you will put in the loop can written as a method for single items, which would make it re-usable, I would also consider the List.ForEach(...);
method.
Info: http://msdn.microsoft.com/en-us/library/bwabdf9z%28v=vs.110%29.aspx
In case you'd be really after performance (which may happen even in C#), the for loop is usually the fastest, though less readable as less concise code: Info: In .NET, which loop runs faster, 'for' or 'foreach'?
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