so i have a list where i need to add new values constantly but when i do i need to increment it and insert it in between two values.
List initiali
List<int> initializers = new List <int>();
initializers.Add(1);
initializers.Add(3);
int index = initializers.IndexOf(3);
initializers.Insert(index, 2);
Gives you 1,2,3.
Use List<T>.Insert:
initializers.Insert(index, value);
For those who are looking for something more complex (inserting more than one item between 2 values, or don't know how to find the index of an item in a list), here is the answer:
Insert one item between 2 values is dead easy, as already mentioned by others:
myList.Insert(index, newItem);
Insert more than one item also is easy, thanks to InsertRange method:
myList.InsertRange(index, newItems);
And finally using following code you can find the index of an item in list:
var index = myList.FindIndex(x => x.Whatever == whatever); // e.g x.Id == id
Another approach, if there is a computationally viable way of sorting the elements, is:
list.Insert(num);
// ...
list.Insert(otherNum);
// Sorting function. Let's sort by absolute value
list.Sort((x, y) => return Math.Abs(x) - Math.Abs(y));
You can just use List.Insert() instead of List.Add() to insert items at a specific position.