Reputation: 53243
Is it possible to mark a foreach loop code block and convert it to a for loop with ReSharper?
Or with Visual Studio?
Thanks!
Upvotes: 9
Views: 7340
Reputation: 328
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
Upvotes: 3
Reputation: 3901
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).
Upvotes: 2
Reputation: 11734
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];
}
Upvotes: 4