46

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.

2

5 Answers 5

77
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.

2
  • Thanks! But what if you don't know if there is a '3' in the list or not? (I just want to add my list item at index 0 no matter what else is in the list)
    – Kokodoko
    Commented Mar 6, 2016 at 15:13
  • You can check if there is a 3 by using Count() and Any() Commented Mar 9, 2023 at 9:54
21

Use List<T>.Insert:

initializers.Insert(index, value);
1
  • i see. i didn't know this existed. lol. new with c#. thanks!!
    – gdubs
    Commented Apr 11, 2012 at 17:39
6

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
4

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

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.