c# list how to insert a new value in between two values

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<int> initializers = new List <int>();

initializers.Add(1);
initializers.Add(3);

so initializers would have 1, 3 values.

i would then process a new set of numbers. the initializers will need to have the values.

1, 5, 3, 7

and if i process another set of numbers it should become

1, 9, 5, 13, 3, 11, 7, 15

i know how to properly generate the new values inserted, i just need some help on inserting it in between the existing values of the initializers without having to add 2 or 3 more loops to move the values’ positions.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

Use List<T>.Insert:

initializers.Insert(index, value);

Method 3

You can just use List.Insert() instead of List.Add() to insert items at a specific position.

Method 4

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

Method 5

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));


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x