Generic List - moving an item within the list

前端 未结 10 724
后悔当初
后悔当初 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 04:57

    Simplest way:

    list[newIndex] = list[oldIndex];
    list.RemoveAt(oldIndex);
    

    EDIT

    The question isn't very clear ... Since we don't care where the list[newIndex] item goes I think the simplest way of doing this is as follows (with or without an extension method):

        public static void Move(this List list, int oldIndex, int newIndex)
        {
            T aux = list[newIndex];
            list[newIndex] = list[oldIndex];
            list[oldIndex] = aux;
        }
    

    This solution is the fastest because it doesn't involve list insertions/removals.

提交回复
热议问题