I declare following object
List<string> list = {"Kate", "John", "Paul", "Eve", "Hugo"};
I would like to move "Eve" at front of my list? How can I do that. I must not to reorder other elements!
At output I want to get this
"Eve", "Kate", "John", "Paul", "Hugo"
list.Remove("Eve"); // Removes the first "Eve" element in the list
list.Insert(0, "Eve"); // Inserts "Eve" at the first position in the list
However, if your list contains multiple "Eve"s, calling Remove("Eve") will only remove the first occurrence of "Eve".
And you have to know that inserting element at the beginning of a list is an expensive operation. Because all elements already in the list have to be shifted.
As @AlvinWong commented, LinkedList<string>
is a very good solution to avoid this overhead when inserting an element. The Insert
operation is done in O(1) (O(n-i) in a List
). The major drawback of LinkedList<string>
is that accessing the i
th element is an operation in O(i) (O(1) in a List
).
You can use the List.RemoveAt
(so you don't remove all Eve's) and List.Insert
.
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