Edit

Share via


Refactoring to convert LINQ to a foreach statement

Use this refactoring to convert LINQ query syntax to a foreach statement.

This refactoring applies to:

  • C#

  • Visual Basic

How to use it

  1. Select the entire LINQ query starting with from.

    Note

    This refactoring can only be used to convert LINQ queries expressed with query syntax and not method syntax.

  2. Press Ctrl+. or click the screwdriver screwdriver icon icon in the margin of the code file.

    Convert LINQ to foreach quick actions menu

  3. Select Convert to 'foreach'. Or, select Preview changes to open the Preview Changes dialog, and then select Apply.

Note

For C#, the code generated by these refactorings uses either an explicit type or var for the iteration variable of the foreach loop. The type in the generated code, explicit or implicit, depends on the code-style settings that are in scope. These particular code-style settings are configured at the machine level under Tools > Options > Text Editor > C# > Code Style > General > 'var' preferences, or at the solution level in an EditorConfig file. If you change a code-style setting in Options, reopen the code file for the changes to take effect.

See also