ForEach to Linq
- 2 minutes to read
Purpose
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:
- Where
- Select
- Cast
- Distinct
- FirstOrDefault
- LastOrDefault
- Aggregate
- Any
- All
- Count
Availability
Available when the caret is on a foreach keyword and the loop body can be converted into a LINQ query.
Usage
Place the caret on a foreach keyword.
Note
The blinking cursor shows the caret’s position at which the Refactoring is available.
- 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;
}
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);