Generic List - moving an item within the list

前端 未结 10 723
后悔当初
后悔当初 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条回答
  •  臣服心动
    2020-11-28 05:21

    Insert the item currently at oldIndex to be at newIndex and then remove the original instance.

    list.Insert(newIndex, list[oldIndex]);
    if (newIndex <= oldIndex) ++oldIndex;
    list.RemoveAt(oldIndex);
    

    You have to take into account that the index of the item you want to remove may change due to the insertion.

提交回复
热议问题