Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a method in the declaration of a foreach

Tags:

c#

foreach

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.

like image 913
CSharpNewBee Avatar asked Jan 29 '14 13:01

CSharpNewBee


People also ask

How do you use the forEach method?

JavaScript Array forEach() The forEach() method calls a function for each element in an array. The forEach() method is not executed for empty elements.

Is forEach a callback function?

The forEach() method calls a specified callback function once for every element it iterates over inside an array.

How does forEach loop work in JavaScript?

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.


2 Answers

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;
        // ...
    }
}
like image 59
Marc Gravell Avatar answered Oct 23 '22 07:10

Marc Gravell


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'?

like image 35
TTT Avatar answered Oct 23 '22 07:10

TTT