Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving a member of a List to the Front of the List

Tags:

c#

.net

How would one create a method that takes an integer i, and move the member of a List<T> at index i from its current position to the front of the list?

like image 276
Shonna Avatar asked Apr 04 '10 19:04

Shonna


1 Answers

The List<T> class doesn't offer such a method, but you can write an extension method that gets the item, removes it and finally re-inserts it:

static class ListExtensions
{
    static void MoveItemAtIndexToFront<T>(this List<T> list, int index)
    {
        T item = list[index];
        list.RemoveAt(index);
        list.Insert(0, item);
    }
}
like image 51
dtb Avatar answered Oct 05 '22 14:10

dtb