我需要重新排列项目列表,以便所选项目进入列表末尾,最后一项替换前一项,前一项替换之前的项目,依此类推。
例如,如果我有一个包含 10 个项目的列表,并且所选项目位于位置 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);
结果是:
0,1,2,3,4,6,7,8,9,5
我确定我的代码丑陋且效率低下:我有两个问题:
- 是否有可能使用 Lambda 获得相同的结果?如果不能,则
- 我怎样才能改进我的代码。谢谢。
最佳答案
您可以使用 Remove Method删除所选项目和 Add Method将其附加在末尾:
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);
之前:
0 2 4 6 8 10 12 14 16 18
删除后(6):
0 2 4 8 10 12 14 16 18
添加后(6):
0 2 4 8 10 12 14 16 18 6
如果你想移动选定索引处的项目,你可以使用 RemoveAt Method而不是 Remove Method :
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);
之前:
0 2 4 6 8 10 12 14 16 18
在 RemoveAt(5) 之后:
0 2 4 6 8 12 14 16 18
添加 (10) 后:
0 2 4 6 8 12 14 16 18 10
使用 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();
numList:
0 2 4 6 8 10 12 14 16 18
新数字列表:
0 2 4 6 8 12 14 16 18 10
关于c# - 使用 lambda 重新排列 List<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7351558/