通用列表 - 在列表中移动一个项目 [英] Generic List - moving an item within the list

查看:30
本文介绍了通用列表 - 在列表中移动一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个通用列表,以及一个 oldIndex 和一个 newIndex 值.

我想将 oldIndex 中的项目移动到 newIndex...尽可能简单.

有什么建议吗?

注意

该项目应位于 (newIndex - 1)newIndex 之前 的项目之间.

解决方案

我知道你说的是通用列表",但你没有指定你需要使用 List(T) 类所以这是一个不同的东西.

ObservableCollection(T) 类有一个 Move方法完全符合您的要求.

public void Move(int oldIndex, int newIndex)

在它下面基本上是这样实现的.

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

所以你可以看到其他人建议的交换方法本质上是 ObservableCollection 在它自己的 Move 方法中所做的.

UPDATE 2015-12-30:您可以查看 移动MoveItem 在 corefx 中的方法现在自己使用,而无需使用 Reflector/ILSpy,因为 .NET 是开源的.>

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

I want to move the item at oldIndex, to newIndex...as simply as possible.

Any suggestions?

Note

The item should be end up between the items at (newIndex - 1) and newIndex before it was removed.

解决方案

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.

这篇关于通用列表 - 在列表中移动一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆