我需要重新排列项目列表,以便所选项目到达列表的末尾,最后一项替换前一项目,前一项目替换之前的项目,依此类推.
例如,如果我有一个包含十个项目的列表,并且所选项目位于第5位,则此项目将转到位置9,而9将替换为8然后8替换7和7替换6和6取代位置5.我设法获得了使用此代码的所需结果:
List<int> numList = new List<int>();
int selectedNum = 5;//Selected at runtime
for (int i = 0; i < 10; i++) numList.Add(i);
int numListCount = numList.Count-1;
int tempNum = numList[numListCount];
List<int> tempList = numList.GetRange(selectedNum + 1,(numList.Count-selectedNum) - 2);
numList[numListCount] = selectedNum;
numList.RemoveRange(selectedNum, (numList.Count-selectedNum)-1);
numList.InsertRange(selectedNum, tempList);
numList.Insert(numListCount - 1, tempNum);
Run Code Online (Sandbox Code Playgroud)
结果是:
0,1,2,3,4,6,7,8,9,5
我确定我的代码很丑陋且效率低下:我有两个问题:
您可以使用" 删除方法"删除所选项目,使用" 添加方法"将其追加到末尾:
List<int> numList = new List<int>();
for (int i = 0; i < 10; i++) numList.Add(2 * i);
int selectedNum = 6; // selected at runtime
numList.Remove(selectedNum);
numList.Add(selectedNum);
Run Code Online (Sandbox Code Playgroud)
之前:
0 2 4 6 8 10 12 14 16 18
Run Code Online (Sandbox Code Playgroud)
删除后(6):
0 2 4 8 10 12 14 16 18
Run Code Online (Sandbox Code Playgroud)
添加(6)后:
0 2 4 8 10 12 14 16 18 6
Run Code Online (Sandbox Code Playgroud)
如果要在选定索引处移动项目,可以使用RemoveAt方法而不是删除方法:
List<int> numList = new List<int>();
for (int i = 0; i < 10; i++) numList.Add(2 * i);
int selectedIndex = 5; // selected at runtime
int selectedNum = numList[selectedIndex];
numList.RemoveAt(selectedIndex);
numList.Add(selectedNum);
Run Code Online (Sandbox Code Playgroud)
之前:
0 2 4 6 8 10 12 14 16 18
Run Code Online (Sandbox Code Playgroud)
在RemoveAt(5)之后:
0 2 4 6 8 12 14 16 18
Run Code Online (Sandbox Code Playgroud)
添加(10)后:
0 2 4 6 8 12 14 16 18 10
Run Code Online (Sandbox Code Playgroud)
使用LINQ,您将创建一个新列表,其中删除并附加所选项.如上所示的就地更新效率更高.
List<int> numList = new List<int>();
for (int i = 0; i < 10; i++) numList.Add(2 * i);
int selectedIndex = 5; // selected at runtime
List<int> newNumList = numList.Take(selectedIndex)
.Concat(numList.Skip(selectedIndex + 1))
.Concat(numList.Skip(selectedIndex).Take(1))
.ToList();
Run Code Online (Sandbox Code Playgroud)
numList:
0 2 4 6 8 10 12 14 16 18
Run Code Online (Sandbox Code Playgroud)
newNumList:
0 2 4 6 8 12 14 16 18 10
Run Code Online (Sandbox Code Playgroud)