Generic List - moving an item within the list

前端 未结 10 728
后悔当初
后悔当初 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:05

    I would expect either:

    // Makes sure item is at newIndex after the operation
    T item = list[oldIndex];
    list.RemoveAt(oldIndex);
    list.Insert(newIndex, item);
    

    ... or:

    // Makes sure relative ordering of newIndex is preserved after the operation, 
    // meaning that the item may actually be inserted at newIndex - 1 
    T item = list[oldIndex];
    list.RemoveAt(oldIndex);
    newIndex = (newIndex > oldIndex ? newIndex - 1, newIndex)
    list.Insert(newIndex, item);
    

    ... would do the trick, but I don't have VS on this machine to check.

提交回复
热议问题