Add item to list before specific item

I have a list of items, say 100 items. I need to add another element in front of an existing element that matches my state. What is the fastest way and maximum performance optimized for this? i.e:.

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

Maybe I should use a different container?

+4
source share
5 answers

First you can find the index of your element using the FindIndex method :

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

Then Insert on the right side:

 myList.Insert(index,newItem); 

Note that inserting with a given index moves everything else forward (think about finding your element at index 0).

+8
source

Consider using LinkedList<T> . The advantage is that inserting or deleting elements does not require the displacement of any objects. The disadvantage is that items cannot be accessed randomly. You must go through the list starting with the first or last item in order to access the items.

+3
source
 myList.Insert(myList.IndexOf("myValue") - 1, "someOtherValue"); 

You should probably make sure that you first verify that myvalue exists and that it is not at index 0.

+2
source
 int index = myList.IndexOf("myValue"); if (index >= 0) myList.Insert(index, "myNewValue"); 

By the way, you should not change your own collection or list during iteration with each (as in your code above).

+2
source

I assume the list is an array - in this case, you tried to do this with Linq?

 string[] mylist = new string[100]; // init the list List<string> list = keys.ToList(); list.Insert(1,"somethingelse"); mylist = list.ToArray(); // convert back to array if required 

if it is a List , you can skip conversions and use Insert directly.

0
source

Source: https://habr.com/ru/post/1447018/


All Articles