coderushforroslyn-115527-refactoring-assistance-foreach-to-linq.md
Converts a foreach loop into an appropriate LINQ method-based query. LINQ queries can make your code shorter and clearer.
The following LINQ methods are supported:
Available when the caret is on a foreach keyword and the loop body can be converted into a LINQ query.
Place the caret on a foreach keyword.
Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu.
Select ForEach to Linq from the menu.
After execution, the Refactoring converts the foreach loop into an equivalent LINQ query.
static int Process(List<int> items) {
var result = items.Aggregate(10, (accumulator, item) => accumulator *= item -= item * 2);
return result;
}
Function Process(items As List(Of Integer)) As Integer
Dim result As Integer = items.Aggregate(10, Sub(accumulator, item) accumulator *= item -= item * 2)
Return result
End Function
In the example above, you can avoid using the result variable by executing the Inline Temp Refactoring on it. After that, the method contains only one statement, which makes its C# version suitable for applying the Use Expression Body Refactoring. The resulting code looks as follows:
static int Process(List<int> items) => items.Aggregate(10, (accumulator, item) => accumulator *= item -= item * 2);
Function Process(items As List(Of Integer)) As Integer
Return result items.Aggregate(10, Sub(accumulator, item) accumulator *= item -= item * 2)
End Function
See Also