将List的成员移动到List的前面

Sho*_*nna 13 .net c#

如何创建一个取整数的方法,并将at索引i的成员从其当前位置移动到列表的前面?List<T>i

dtb*_*dtb 26

名单<T>类并不提供这样的方法,但你可以编写获取项目的扩展方法,删除它终于重新插入它:

static class ListExtensions
{
    static void MoveItemAtIndexToFront<T>(this List<T> list, int index)
    {
        T item = list[index];
        list.RemoveAt(index);
        list.Insert(0, item);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 好的,既然你知道签名我大胆地宣称这是作业.将其标记为下次. (19认同)
  • @Shonna:该方法需要对列表的引用。您需要将其传入或更改我的代码以以不同的方式访问列表,这应该足够简单。 (2认同)

Fed*_*ede 9

到目前为止,3个答案中的任何一个都有诀窍,但我建议不要执行RemoveAt和Insert操作,而是建议将每个项目从左侧所需的位置向右移动到列表的开头.这样您就可以避免移动放置在项目右侧的项目.

这是@ dtb答案的修改.

static class ListExtensions
{
    static void MoveItemAtIndexToFront<T>(this List<T> list, int index)
    {
        T item = list[index];
        for (int i = index; i > 0; i--)
            list[i] = list[i - 1];
        list[0] = item;
    }
}
Run Code Online (Sandbox Code Playgroud)


vit*_*ore 5

var l = new List<DataItem>();
var temp = l[index];
l.RemoveAt(index);
l.Insert(0, temp);
Run Code Online (Sandbox Code Playgroud)