Generic List - moving an item within the list

前端 未结 10 725
后悔当初
后悔当初 2020-11-28 04:32

So I have a generic list, and an oldIndex and a newIndex value.

I want to move the item at oldIndex, to newIndex.

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 05:13

    I know this question is old but I adapted THIS response of javascript code to C#. Hope it helps

    public static void Move(this List list, int oldIndex, int newIndex)
    {
        // exit if positions are equal or outside array
        if ((oldIndex == newIndex) || (0 > oldIndex) || (oldIndex >= list.Count) || (0 > newIndex) ||
            (newIndex >= list.Count)) return;
        // local variables
        var i = 0;
        T tmp = list[oldIndex];
        // move element down and shift other elements up
        if (oldIndex < newIndex)
        {
            for (i = oldIndex; i < newIndex; i++)
            {
                list[i] = list[i + 1];
            }
        }
            // move element up and shift other elements down
        else
        {
            for (i = oldIndex; i > newIndex; i--)
            {
                list[i] = list[i - 1];
            }
        }
        // put element from position 1 to destination
        list[newIndex] = tmp;
    }
    

提交回复
热议问题