Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add element to list before specific element

Tags:

c#

list

I have a list of items, lets say 100 items. I need to add another element before the existing element that matches my condition. What is the fastest way and the most performance optimized to do this? ie.:

foreach (var i in myList)
{
    if (myList[i].value == "myValue")
    {
        myList[i-1] add ("someOtherValue")
    }
}

Maybe i should use other container?

like image 261
kul_mi Avatar asked Nov 19 '12 16:11

kul_mi


People also ask

How do you add an element to a specific position in a list?

Enter the item to be inserted into the list and create a variable to store it. Use the insert() function(inserts the provided value at the specified position) to insert the given item at the first position(index=0) into the list by passing the index value as 0 and the item to be inserted as arguments to it.

How do you add items to the middle of a list in Python?

insert() Method. Use the insert() method when you want to add data to the beginning or middle of a list. Take note that the index to add the new element is the first parameter of the method.

How do you add an element to an Arraylist at a specific index in Python?

Inserting an element in list at specific index using list. insert() In python list provides a member function insert() i.e. It accepts a position and an element and inserts the element at given position in the list.


1 Answers

First you could find the index of your item using FindIndex method:

var index = myList.FindIndex(x => x.value == "myvalue");

Then Insert at the right point:

myList.Insert(index,newItem);

Note that inserting at a given index pushes everything else forward (think about finding your item at index 0).

like image 129
Jamiec Avatar answered Oct 05 '22 05:10

Jamiec