Back to Devexpress

ForEach to Linq

coderushforroslyn-115527-refactoring-assistance-foreach-to-linq.md

latest2.2 KB
Original Source

ForEach to Linq

  • Aug 03, 2020
  • 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

  1. Place the caret on a foreach keyword.

  2. Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu.

  3. Select ForEach to Linq from the menu.

After execution, the Refactoring converts the foreach loop into an equivalent LINQ query.

csharp
static int Process(List<int> items) {
    var result = items.Aggregate(10, (accumulator, item) => accumulator *= item -= item * 2);
    return result;
}
vb
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:

csharp
static int Process(List<int> items) => items.Aggregate(10, (accumulator, item) => accumulator *= item -= item * 2);
vb
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

ForEach to For/For to ForEach