Alex
Alex

Reputation: 9720

Change items position in List<string>

I have one list with 3 items

reg.ToList()    Count = 3   System.Collections.Generic.List<string>
[0] "Text0" string
[1] "Text1" string
[2] "Text2" string

I want to change all item positions, first postion instead last one, and remaining items to stand up with one position

for this example

[0] "Text1" string
[1] "Text2" string
[2] "Text0" string

Upvotes: 4

Views: 13382

Answers (2)

Crono
Crono

Reputation: 10478

Use RemoveAt method right after getting ahold of your first item, then add it back.

var item = list[0];
list.RemoveAt(0);
list.Add(item);

RemoveAt will be more efficient than Remove because it won't try to search through your list and compare values needlessly.

Upvotes: 12

Schuere
Schuere

Reputation: 1649

you could remove and re-add the first item in the list. This way your value will be at the end of the list

var item = reg[0];
reg.Remove(item); //Removes the specific item
reg.Add(item); //add's an item to the end of the list

this will also work with bigger lists and the index will change accordingly

EDIT: Crono's solution will work faster then mine :s

Upvotes: 6

Related Questions