tags:

views:

85

answers:

4

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?

+3  A: 

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);
    }
}
dtb
Nice extension.
vittore
the header for the method is supposed to be like this:public void MoveToFront(int i)
Shonna
Okay, since you _know_ the signature I'm boldly claiming that this is homework. Tag it as that next time.
Benjamin Podszun
@Shonna: the method needs a reference to the list. You need to pass that in or change my code to access the list in a different way which should be simple enough.
dtb
A: 
var l = new List<DataItem>();
var temp = l[index];
l.RemoveAt(index);
l.Insert(0, temp);
vittore
+1  A: 

Try this

    static List<int> idList = new List<int>() { 1, 2, 4, 5, 6, 8, 9 };

    private static void moveListItem(int index)
    {
        int getIndex = 0;

        foreach (int item in idList)
        {
            Console.WriteLine(" Before Id List Value - {0} ,Index - {1} ", item.ToString(), getIndex);
            getIndex++;
        }

        int value = idList[index];
        idList.RemoveAt(index);
        idList.Insert(0, value);

        Console.WriteLine();

        getIndex = 0;
        foreach (int item in idList)
        {
            Console.WriteLine(" After Id List Value - {0} ,Index - {1} ", item.ToString(), getIndex);
            getIndex++;
        }
    }
Wonde
A: 

Any of the 3 answers so far do the trick, but instead of doing a RemoveAt and a Insert operation, I would suggest moving each item one place to the right from the desired positions left, to the beginning of the list. That way you avoid moving the items placed at the right of the item moved.

This is a modification of @dtb's answer.

static class ListExtensions
{
    static void MoveItemAtIndexToFront<T>(this List<T> list, int index)
    {
        T item = list[index];
        for (int i = index; i > 0; i--)
            list[i] = list[i - 1];
        list[0] = item;
    }
}
Fede