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?
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With