coderushforroslyn-115530-refactoring-assistance-foreach-to-for-for-to-foreach.md
This Refactoring is used to switch between the for loop and foreach loop. The foreach loop is more readable and compact. On the other hand, if your algorithm uses the iteration number for calculations, the for loop is more applicable.
Note
In rare cases, the ForEach to For refactoring may change your code’s external behavior if the IEnumerator implementation causes significant side effects, or if any of the IEnumerator members behave in a non-standard manner.
Available when the caret is on the for or foreach keyword.
Place the caret on a foreach keyword.
Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu.
Select ForEach to For from the menu ( For to ForEach if you are converting the for loop to foreach loop).
After execution, the Refactoring converts the foreach loop to a for loop or vice versa.
string result = String.Empty;
for (int i = 0; i < strings.Count; i++)
if (strings[i].Length > 2)
result += $"{strings[i]} ";
Dim result As String = String.Empty
For i As Integer = 0 To Strings.Count - 1
If Strings(i).Length > 2 Then
result &= $"{Strings(i)} "
End If
Next i
See Also