Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move elements in list

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"
like image 585
Jacek Avatar asked Jan 31 '13 15:01

Jacek


2 Answers

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.

UPDATE

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 ith element is an operation in O(i) (O(1) in a List).

like image 165
Cédric Bignon Avatar answered Sep 19 '22 16:09

Cédric Bignon


You can use the List.RemoveAt (so you don't remove all Eve's) and List.Insert.

like image 35
Grant Thomas Avatar answered Sep 21 '22 16:09

Grant Thomas