Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting 'foreach' to 'for' loop or vice versa with ReSharper possible?

Is it possible to mark a foreach loop code block and convert it to a for loop with ReSharper?

Or with Visual Studio?

Thanks!

like image 912
pencilCake Avatar asked Jun 18 '10 13:06

pencilCake


3 Answers

Yep ReShaper can do that. Tested it in VS2010 + R#5

Before:

        var a = new int[] {1, 2, 3, 4};
        foreach (var i in a)
        {

        }

After:

    var a = new int[] {1, 2, 3, 4};
    for (int index = 0; index < a.Length; index++)
    {
        var i = a[index];
    }
like image 196
Ralf de Kleine Avatar answered Nov 01 '22 13:11

Ralf de Kleine


You can even do this without Resharper now (Tested with Visual Studio 2017 on a C# project):

int[] array = new int[3] { 1, 2, 3 };

foreach (int item in array)
{
   int someVariable = item;
   //Your logic
}

Becomes

int[] array = new int[3] { 1, 2, 3 };

for (int i = 0; i < array.Length; i++)
{
   int item = array[i];
   int someVariable = item;
  //Your logic
}

(And vice versa!) To make this change, you just have to click on the "foreach" or "for" word, and look for a screwdriver icon shown on the left, click on it and select "convert to 'for'" / "convert to 'foreach'". (see the link below if you never saw this icon)

Hope it helped someone (even if this is a very old post!)

Visual Studio screwdriver icon

like image 40
Thanaen Avatar answered Nov 01 '22 13:11

Thanaen


works fine, just as rdkleine said and the sample is working great.
BUT: it if your collection is a simple IEnumerable<T> it won't work (reasonably).

like image 2
Tamir Avatar answered Nov 01 '22 13:11

Tamir