开发者

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

How would one create a method that takes an integer i, and move the member of a List<T&g开发者_运维知识库t; at index i from its current position to the front of the list?


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);
    }
}


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;
    }
}


var l = new List<DataItem>();
var temp = l[index];
l.RemoveAt(index);
l.Insert(0, temp);


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++;
        }
    }


At the risk of beating a dead horse:

Wouldn't a LinkedList be more suited for this? Although you would loose the random access functionality, inserting elements at the beginning of the List would be much simpler (.AddFirst) and a lot more efficient.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜