The purpose of the method is to add a list of items after every nth step (5 for example) where the input items are repeated if needed. I'm looking for an overall review and possible how to remove the use of the while and replace it with a for.
public static List<string> AddEveryNthStep(List<string> items, List<string> itemsToAdd, int nthStep)
{
List<string> output = new List<string>();
int itemIndex = 0;
int itemsToAddIndex = 0;
int index = 1;
while (itemsToAddIndex < itemsToAdd.Count)
{
output.Add(items[itemIndex++]);
if (itemIndex == items.Count)
{
itemIndex = 0;
}
// We are at at point where we want to add a item
if (index % nthStep == 0)
{
output.Add(itemsToAdd[itemsToAddIndex++]);
}
index++;
}
return output;
}
Usage:
List<string> items = new List<string> { "Item 1", "Item 2", "Item 3", "Item 4" };
List<string> itemsToAdd = new List<string> { "Item to add 1", "Item to add 2", "Item to add 3" };
Console.WriteLine(String.Join(Environment.NewLine, AddEveryNthStep(items, itemsToAdd, 5)));
Output:
itemsToAdd
is what I mean. You basically have the outputed values in there. Am I wrong ? \$\endgroup\$ – Denis Apr 21 '16 at 8:53i
is the value in the for you can just check if it's multiple of our nth number. If so we output"item to add {0}",items[i]
this requires you to create anint
array and output"item {0}",array[i]
. Wouldn't that work just fine ? If you want to still output the first indexes you can do an inner for loop that will start atarray.Length - nth number + startingIndex
starting index will incrase with 1 each time a sequence is printed. \$\endgroup\$ – Denis Apr 21 '16 at 8:59