Generic List - moving an item within the list

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

    I know you said "generic list" but you didn't specify that you needed to use the List(T) class so here is a shot at something different.

    The ObservableCollection(T) class has a Move method that does exactly what you want.

    public void Move(int oldIndex, int newIndex)
    

    Underneath it is basically implemented like this.

    T item = base[oldIndex];
    base.RemoveItem(oldIndex);
    base.InsertItem(newIndex, item);
    

    So as you can see the swap method that others have suggested is essentially what the ObservableCollection does in it's own Move method.

    UPDATE 2015-12-30: You can see the source code for the Move and MoveItem methods in corefx now for yourself without using Reflector/ILSpy since .NET is open source.

提交回复
热议问题