gpt4 book ai didi

c# - 使列表中的元素成为第一个元素的最快方法

转载 作者:行者123 更新时间:2023-11-30 22:15:16 25 4
gpt4 key购买 nike

我有一个列表,我想要一个简短而快速的方法来使它的一个元素成为第一个。我想使用下面的代码来选择第 10 个元素并将其放在第一位。但正在寻找更好的解决方案

tempList.Insert(0, tempList[10]);
tempList.RemoveAt(11);

最佳答案

如果你不介意其余的顺序,你实际上可以交换位置 0 和 10 的两个项目,相信这比插入和删除更好:

var other = tempList[0];
tempList[0]=tempList[10];
tempList[10] = other;

您甚至可以将其作为 List 的扩展以便于使用,例如:

 public static void Swap<T>(this List<T> list, int oldIndex, int newIndex)
{
// place the swap code here
}

关于c# - 使列表中的元素成为第一个元素的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18073269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com