❔ Filing empty list with equal items left and right of selected item from another list

Given a list and selected index of an item in that list, I want to fill another list such that items will try to be inserted, in order, to the left and right of that selected item without going past a given max count for the new list. A little confusing, but here's an example:
I have a list with the following strings { "red", "blue", "green", "yellow", "black", "brown" }. I am given the index 3 which corresponds to the element yellow in the list. I want to populate a new list that, given a max of 5, looks like the following:

{ "blue", "green", "yellow", "black", "brown" }

So essentially I try to keep the original selected item in the middle of a new list and insert items from the original list to the left and right until I hit the max. If there's not enough elements to reach the max then it's fine if it's not in the middle.

This is what I have so far, and it's fine and works, but I'm not sure if there's a more efficient way or using less for loops and if statements.

int idx = originalList.IndexOf(selectedItem); int count = 1; newList.Add(selectedItem); // first add the selecteditem to the new list // first try to get two elements before the selected item int lastBeforeIndx = idx; for (int i = idx - 1; i >= 0; i--) { if (count == 3) { break; } newList.Insert(0, originalList[i]); lastBeforeIndx = i; count++; } // then try to get 2 elements to the right of the selected item for (int i = idx + 1; i <= originalList.Count; i++) { if (count == 5) { break; } newList.Add(originalList[i]); count++; } // all finished. Only want to show five at a time in this example if (count == 5) { return; } // if not at 5, try adding to the left again for (int i = lastBeforeIndx - 1; i >= 0; i--) { if (count == 5) { break; } newList.Insert(0, originalList[i]); count++; }
Was this page helpful?